矢量订阅超出范围,如何消除此错误
Vector subscription out of range, how do I eliminate this error?
这是代码:
#include "stdafx.h"
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
inline void keep_window_open() { char ch; cin >> ch; }
int main()
{
string name = "lol";
int score = 0;
vector<string>names;
vector<int>scores;
bool choose = true;
for (int l = 0; name != "stop"; ++l) {
cin >> name >> score;
if (name == names[l]) choose = false;
if (choose == true) {
names.push_back(name);
scores.push_back(score);
}
else cout << "error, name already used" << endl;
choose = true;
}
}
当我运行程序时,我键入一个名称后跟一个分数,它说:"调试断言失败:矢量订阅超出范围"。为什么?我该如何消除此错误?
你尝试获取不存在的元素。首先,您需要推送一些东西
vector<string> names;
或者检查名称是否为空:
if (!names.empty())
if(name == names[l])
choose = false;
还看你想要实现什么,似乎你无论如何都有错误的代码,你只看你添加的姓氏。因此,为了帮助您,此解决方案效果更好:
int main()
{
string name;
vector<string> names;
while (cin >> name && name != "stop")
{
bool choose = true;
for (auto i : names)
{
if (name == i)
choose = false;
}
if (choose)
{
names.push_back(name);
}
else cout << "error, name already used" << endl;
}
}
相关文章:
- 警告处理为错误这里有什么问题
- "error: no matching function for call to"构造函数错误
- boost::进程间消息队列引发错误
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 有关插入适配器的错误。[错误]请求从 'back_insert_iterator<vector<>>' 类型转换为非标量类型
- QT在错误的班级中寻找空位
- vector.resize()中的分配错误
- 代码在main()中运行,但在函数中出现错误
- 释放错误后堆使用
- (C++)分析树以计算返回错误值的简单算术表达式
- Project Euler问题4的错误解决方案
- 我的字符计数代码计算错误.为什么
- 从"int*"强制转换为"unsigned int"会丢失精度错误
- 尝试导入pybind-opencv模块时出现libgtk错误
- CMake项目Boost库错误:Boost/config/compiler/gcc.hpp:165:10:致命错误:cs
- 在某些循环内使用vector.push_back时出现分段错误
- MSVC多行宏编译器错误
- 静态数据成员的问题-修复链接错误会导致编译器错误
- 错误:' template '(作为消歧器)只允许在模板中使用
- 执行高斯消去程序时结果错误