简体   繁体   中英

C++ vector subscript out of range

I keep getting this error when I try to run my program after compiling it:

vector subscript out of range

my code is like :

for (int i=1; i<=n; i++) {
    getline(input, line);
    istringstream iss(line);
    iss >> num;
    while (!iss.eof()) {
        iss >> o;
        b.push_back(o);
    }
    sort(b.begin(), b.end);
    se = b.size();
    output << num << " " << b[se-1] << endl;
    b.clear();
    b.resize(100);
}

And the file looks like:

3
1 5 6 1 3 50 600
2 4 5 7 8 3 6
4 1 2 3 4 5 6

So , where is the problem?

sort (b.begin(),b.end);

You're using the address of b's end function to sort , not the iterator that b.end() would return had you called it, so the sort algorithm will stumble off the end of your vector, which causes the 'subscript out of range' error you're reporting. (If you had iterator debugging disabled, it'd do far worse than reporting that error!)

This should be

sort (b.begin(),b.end());

edit

You might also want to check that your vector isn't empty, as that's another place you could be referencing outside of its bounds:

se = b.size();
if( se > 0 )
    output << num << " " << b[se-1] << endl;

You store the first number in a line in the num variable, and only subsequent numbers in the vector. So the first time you call output<<num<<" "<<b[se-1]<<endl; the vector b is empty, and the expression se-1 is -1, which is out of range.

You've not posted the actual code (since the code you posted won't compile), and you've not given us any hint about the types involved. But if num and o are numeric types, and b is a vector of numeric types, and there is no additional white space between the 3 and the end of line in the first line, the first time through the loop, you'll probably (almost certainly) not enter the while , b will be empty ( b.size() == 0 ), and b[se - 1] will attempt to access some incredible large index in an empty array.

Of course, if num is complex , or some other type for which "3" is not a legal value, you'll enter an endless loop with while (!iss.eof()) . The correct form of the loop would be:

while ( iss >> o ) {
    b.push_back( o );
}

The fact that you use the value o without checking whether you've actually succeeded in reading it can result in undefined behavior.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM