C++ 如何调整大小并打印比我拥有的更小的值?
我想减少我的程序的向量。基本上打印出较小的值。例如,我设法寻找我需要的东西,但我不能减少它。我作为CC寻找第一选择,并得到了它。我还设法按GPA排序。它给了我5个输出,这是正确的,但我只需要最高GPA的3。我不知道我的方法是否可行 这是我的txt文件的一个片段: 顺序是第一、第二、第三、GPA、名称C++ 如何调整大小并打印比我拥有的更小的值?,c++,C++,我想减少我的程序的向量。基本上打印出较小的值。例如,我设法寻找我需要的东西,但我不能减少它。我作为CC寻找第一选择,并得到了它。我还设法按GPA排序。它给了我5个输出,这是正确的,但我只需要最高GPA的3。我不知道我的方法是否可行 这是我的txt文件的一个片段: 顺序是第一、第二、第三、GPA、名称 CC,DR,TP,3.8,AlexKong SN,SM,TP,4.0,JasonTan DR,TP,SC,3.6,AstaGoodwin SC,TP,DR,2.8,MalcumYeo SN,SM,T
CC,DR,TP,3.8,AlexKong
SN,SM,TP,4.0,JasonTan
DR,TP,SC,3.6,AstaGoodwin
SC,TP,DR,2.8,MalcumYeo
SN,SM,TP,3.7,DavidLim
SN,SM,TP,3.2,SebastianHo
SC,TP,DR,4.0,PranjitSingh
and so on...
下面是我的代码:
while (File >> line) //parse all the lines
{
v.push_back(line);
}
cout << "\nCC Students: " << endl;
for (auto str : v){
sort(v.begin(), v.end(), greater());
if (!str.find("CC")){
cout << str.substr(13, 100) << " " << str.substr(9, 3) << "\n"; //will print all fields where CC is found
}
}
在那之后,我意识到我不能轻易地调整它的大小。然后我更新了它。我尝试搜索第一个元素是否为CC,然后尝试将所有元素放在一个新的向量中,这样我可以调整它的大小并显示较小的值
sort(v.begin(), v.end(), greater());
for (auto str : v){
if (!str.find("CC")){ //tried to search for all the lines with CC as first choice
vector <string> CC; //tried to create a new vector to put the lines
string line;
while (File >> line) //parse all the lines
{
CC.push_back(line); //tried to put the lines into one vector.
CC.resize(3); //tried to resize so that I can only print top 3.
}
cout << str.substr(13, 100) << " " << str.substr(9, 3) << "\n"; //will print all fields where CC is found
}
但很明显我在某个地方做错了什么。我不知道我的逻辑是错的还是我做得不对。我希望有人能指出我做错了什么,并引导我前进。我不擅长这一点,所以为所有这些奇怪的尝试道歉,但我希望我能告诉你我这么做的意思。
提前谢谢
CC
向量移到循环外CC
的大小为3while(File>>line)//解析所有行
{
v、 向后推(线);
}
排序(v.begin(),v.end(),greater());
谢谢你,先生。代码是有效的。非常感谢。我从来不知道我可以利用休息;我以前从没用过。无论如何,再次谢谢你。当心!
sort(v.begin(), v.end(), greater());
for (auto str : v){
if (!str.find("CC")){ //tried to search for all the lines with CC as first choice
vector <string> CC; //tried to create a new vector to put the lines
string line;
while (File >> line) //parse all the lines
{
CC.push_back(line); //tried to put the lines into one vector.
CC.resize(3); //tried to resize so that I can only print top 3.
}
cout << str.substr(13, 100) << " " << str.substr(9, 3) << "\n"; //will print all fields where CC is found
}
MuruArun 3.9
AlexKong 3.8
DamianKoh 3.7
while (File >> line) //parse all the lines
{
v.push_back(line);
}
sort(v.begin(), v.end(), greater());
cout << "\nCC Students: " << endl;
std::vector<std::string> CC;
for (auto str : v)
{
if (str.find("CC") == 0)
{
CC.push_back(str);
if (CC.size() == 3)
break;
}
}
// now do whatever you want with CC. It has at-most three
// lines in it, and all of them start with CC.
while (File >> line) //parse all the lines
{
v.push_back(line);
}
sort(v.begin(), v.end(), greater());
cout << "\nCC Students: " << endl;
int cc = 0;
for (auto str : v)
{
if (str.find("CC") == 0)
{
// TODO: print whatever you want from the current line.
// ...then
if (++cc == 3)
break;
}
}