【问题标题】:Vector subscript out of range error, C++向量下标超出范围错误,C++
【发布时间】:2011-07-06 21:38:53
【问题描述】:

当我尝试运行这个程序时,我收到一个错误,它会停止程序并显示“向量下标超出范围”

知道我做错了什么吗?

#include <vector>
#include <string>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;

//(int argc, char* argv[]
int main()
{
    fstream bookread("test.txt");
    vector<string> words;

    bookread.open("test.txt");
    if(bookread.is_open()){
        cout << "opening textfile";
        while(bookread.good()){
            string input;
            //getline(bookread, input);
            bookread>>input;
            //string cleanedWord=preprocess(input);         
            //char first=cleanedWord[0];
            //if(first<=*/
            //cout << "getting words";
            //getWords(words, input);
        }
    }
    cout << "all done";

    words[0];

getchar();
}

【问题讨论】:

标签: c++ file vector


【解决方案1】:

你永远不会在vector这个词中插入任何东西,所以words[0];这一行是非法的,因为它访问了它的第一个元素,而这个元素并不存在。

【讨论】:

  • 我在while循环中添加了words.push_back(input),还是报错
  • 如果程序实际到达此行,请检查附加的调试器。我不这么认为。
  • 它说错误是第 779 行?但是程序显然没有那么长
  • 这是向量头中导致调试断言的行。您需要在words.push_back 处设置断点并检查是否到达。如果不是,你的逻辑有问题。
  • 我在这里没有看到任何关于断点的信息:cplusplus.com/reference/stl/vector/push_back 究竟什么是断点以及如何添加它?
【解决方案2】:

我看不出你将任何东西推到向量上。如果向量为空,则下标 0 将超出范围。

【讨论】:

    【解决方案3】:

    您的程序似乎永远不会向向量中添加任何内容,通常使用push_back() 完成,因此在运行时words[0] 会产生您的subscript out of range 错误。

    您应该在访问它之前检查矢量的大小。

    试试这个:

    for(vector<string>::const_iterator it=words.begin(), end=words.end(); it!=end; ++it){
      cout << *it << ' ';
    }
    

    【讨论】:

      【解决方案4】:

      您能否附上您在向量上实际 push_back 字符串的代码版本。除非可以查看重现的代码,否则无法调试问题。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-05-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多