c++向量push_back问题
c++ vector push_back problems
我的练习代码有问题。如果我输入名称和分数值,这些值不会被推入向量中。这是我的代码:
#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语句,在该语句中,值被推送到向量中,但它不推送向量中的值。
这里的问题是names
和scores
在while循环中声明。这意味着它们被构造、使用,然后被销毁的每一次迭代。这意味着在每次迭代中都有新的向量。您需要将向量移出循环,以便它们在整个循环执行过程中保持不变。
vector<string> names = {"test"};
vector<int> scores = {0};
while(true)
{
string name = "none";
int score = 0;
...
}
相关文章:
- 警告处理为错误这里有什么问题
- 最小硬币更换问题(自上而下方法)
- 为"adjacent"变量赋值时出现问题
- 我的神经网络不起作用 [XOR 问题]
- 在Ubuntu 16.04上安装Cilk时出现问题
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 编译包含字符串的代码时遇到问题
- Project Euler问题4的错误解决方案
- 问题:什么是QAbstractItemView::NoEditTriggers的反面
- 在编译C++代码(具有dlib和opencv)到WASM时面临问题
- 在进程中对同一管道进行读取和写入时C++管道出现问题
- 静态数据成员的问题-修复链接错误会导致编译器错误
- C++ 雷神库 - 使用资源加载器类时出现问题(不命名类型)
- 一个关于在C++中重载布尔运算符的问题
- 首要问题的答案让值班员搞错了
- setlocale的C++土耳其字符串问题
- 如何重构类层次结构以避免菱形问题
- 基于boost的程序的静态链接——zlib问题
- C++格式化输出问题
- 使用mongocxx驱动程序时包含头文件问题