c++ - vector 循环无法正常运行

标签 c++ arrays loops for-loop vector

我正在尝试编写一个程序,它需要 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/

相关文章:

javascript - 如何在javascript中交替使用2个循环?

c++ - 将任何指针传递给要删除的函数

PHP:数组似乎重新初始化

xcode - Xcode StoryboardSegue循环回到同一 View

python - 使用 NumPy 数组执行分组平均值和标准差

c - 动态分配数组,无需 malloc 和 calloc

c - 通过循环将数组传递给 "isalpha"

c++ - 指向 shared_ptr 成员变量的指针

c++ - 屏幕截图特定窗口

c++ - 在 C++ 中有一个 HashMap 的复合键