c++向量push_back问题

c++ vector push_back problems

本文关键字:back 问题 push 向量 c++      更新时间:2023-10-16

我的练习代码有问题。如果我输入名称和分数值,这些值不会被推入向量中。这是我的代码:

#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语句,在该语句中,值被推送到向量中,但它不推送向量中的值。

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

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