我正在尝试编写一个程序,它需要 10 个吃煎饼的人,然后返回吃煎饼最多的人,我正在使用 vector 以便在用户输入时创建新元素并稍后返回它们,我尝试使用数组,但遇到了困难。
#include <iostream>
#include <vector>
using namespace std ;
int main()
{
int lnum , input ;
int temp = 0;
vector <int> persons(10) ;
cout << "This program takes input for 10 people who ate pancakes, \
then checks who ate the most pancakes " << endl;
cout << "Enter the amount of pancakes each person ate: " << endl ;
cout << "Person 1: " ;
cin >> input ;
persons.push_back(input);
cout << "Person 2: " ;
cin >> input ;
persons.push_back(input);
cout << "Person 3: " ;
cin >> input ;
persons.push_back(input);
cout << "Person 4: " ;
cin >> input ;
persons.push_back(input);
cout << "Person 5: " ;
cin >> input ;
persons.push_back(input);
cout << "Person 6: " ;
cin >> input ;
persons.push_back(input);
cout << "Person 7: " ;
cin >> input ;
persons.push_back(input);
cout << "Person 8: " ;
cin >> input ;
persons.push_back(input);
cout << "Person 9: " ;
cin >> input ;
persons.push_back(input);
cout << "Person 10: " ;
cin >> input ;
persons.push_back(input);
cout << endl ;
for(int i = 0 ; i < 11; i++){
if(persons.at(i) > temp){
temp == persons.at(i) ;
}
}
cout << temp << endl ;
return 0 ;
}
大多数情况下一切都运行良好,除了当我运行程序时,它返回 temp 为 0,而不是实际数字应该是什么。此外,当我调用像
这样的命令时person.at(1) ;
它返回了不正确的值,我做错了什么,这是逻辑错误还是语法错误?
最佳答案
您可以替换整个部分:
for(int i = 0; i < persons.size(); i++) // note the non-hard-coded conditional
{
if(persons.at(i) > temp)
{
temp = persons.at(i); // note fixed to assignment!
}
}
与
temp = std::max_element(persons.begin(), persons.end());
关于c++ - vector 循环无法正常运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20695894/