从文本文件读取vector时报“vector subscript out of range”错误的解决方法
修复vector下标越界问题:读取文本到vector的正确姿势
嘿,我看了你的代码,问题其实挺典型的,咱们一步步拆解:
首先,触发vector subscript out of range的核心原因是你直接用下标访问了空的vector。你的band是个vector,默认初始化后是空的(size为0),但你直接写band[i]去赋值——vector的下标操作只能访问已经存在的元素,不能用来新增元素,这就直接踩了越界的坑。
另外你代码里还有两个小bug:
- 读取乐队的循环条件写了
i <= bandnum,比如文本里bandnum是3的话,你会读4个元素,把后面的singer也读进乐队列表里,导致后面的role读取错误; - 输出乐队的循环条件是
i > bandnum,初始i是0,这条件永远不成立,等于白写,根本不会输出任何内容。
给你改好的代码,你可以参考:
#include <iostream> #include <fstream> #include <vector> #include <string> using namespace std; int main() { ifstream artist("your_artist_file.txt"); // 记得替换成你的实际文件名 string forname, surname, role, band_name; int bandnum; while (artist >> forname >> surname >> bandnum) { vector<string> band; // 先读取bandnum个乐队名称,用push_back自动扩容vector for (int i = 0; i < bandnum; ++i) { artist >> band_name; band.push_back(band_name); } // 输出读取到的内容,用范围for循环更省心 cout << "Name: " << forname << " " << surname << endl; cout << "Bands: "; for (const auto& b : band) { cout << b << " "; } cout << endl; // 读取角色 artist >> role; cout << "Role: " << role << "\n\n"; } artist.close(); return 0; }
重点修改的地方说一下:
- 用
push_back替代下标赋值:vector会自动扩容,完全避免下标越界的问题; - 把读取循环的条件改成
i < bandnum:刚好读取bandnum个乐队名,不会误读后面的角色字段; - 输出用范围for循环:不用手动管理下标,减少出错概率;
- 每次循环重新创建vector(或者你也可以用
band.clear()清空之前的内容):保证每个艺术家的乐队列表互不干扰。
如果想优化性能,可以在读取前给vector预留空间:band.reserve(bandnum);,这样vector会提前分配足够的内存,减少扩容的次数,但这不是必须的,push_back本身已经能解决你的问题。
内容的提问来源于stack exchange,提问作者Sean Heaney
相关产品推荐
相关产品推荐

