C ++向量push_back问题

时间:2018-07-30 18:24:09

标签: c++

我的锻炼代码有问题。如果输入名称和分数值,则不会将值推入向量中。这是我的代码:

#include <iostream>
#include <string>
#include <algorithm>
#include <vector>

using namespace std;

int main()
{
    while(true)
    {
        vector<string> names = {"test"};
        vector<int> scores = {0};

        string name = "none";
        int score = 0;

        cin >> name >> score;
        if(name == "print" && score == 0)
        {
            for(int i = 0;i<names.size();++i)
            {
                cout << "name:" << names[i] << " score:" << scores[i] << "\n";
            }
        }
        if(name == "NoName" && score == 0)
        {
            break;
        }
        if (find(names.begin(), names.end(), name) != names.end())
        {
            cout << name << " found name in names, you can't use this name.\n";
        }else{
            names.push_back(name);
            scores.push_back(score);
        }
    }
} 

正在调用将值推入向量中的else语句,但不会将值推入向量中。

1 个答案:

答案 0 :(得分:6)

您的问题是namesscores在while循环中声明。这意味着每次迭代都会被构造,使用和销毁。这意味着在每次迭代中您都有新鲜的向量。您需要将向量移出循环,以便它们在循环的整个执行过程中都保持不变。

vector<string> names = {"test"};
vector<int> scores = {0};
while(true)
{
    string name = "none";
    int score = 0;
    ...
}