the following code fills the vector with 10 values in first for second for loop i want the elements of vector to be printed.The output is till the cout statement before the j loop.Gives error of vector subscript out of range.

You are watching: C++ vector subscript out of range

#include "stdafx.h"#include "iostream"#include "vector"using namespace std;int _tmain(int argc, _TCHAR * argv<>){ vector v; cout 0; --j) { cout


Regardless of how do you index the pushbacks your vector contains 10 elements indexed from 0 (0, 1, ..., 9). So in your second loop v is invalid, when j is 10.

This will fix the error:

for(int j = 9;j >= 0;--j){ cout In general it"s better to think about indexes as 0 based, so I suggest you change also your first loop to this:

for(int i = 0;i Also, to access the elements of a container, the idiomatic approach is to use iterators (in this case: a reverse iterator):

for (vector::reverse_iterator i = v.rbegin(); i != v.rend(); ++i){ std::cout


v has 10 element, the index starts from 0 to 9.

for(int j=10;j>0;--j){ coutyou should update for loop to

for(int j=9; j>=0; --j)// ^^^^^^^^^^{ coutOr use reverse iterator to print element in reverse order

for (auto ri = v.rbegin(); ri != v.rend(); ++ri){ std::cout


this type of error usually occur when you try to access data through the index in which data data has not been assign. for example

//assign of data in to arrayfor(int i=0; i=0; i--){cout the code will give error (vector subscript out of range)because you are accessing the arr<10> which has not been assign yet.


Thanks for contributing an answer to Stack Overflow!

Please be sure to answer the question. Provide details and share your research!

But avoid

Asking for help, clarification, or responding to other answers.Making statements based on opinion; back them up with references or personal experience.

See more: Hy-Gain Av-18Vs Review S: Hy

To learn more, see our tips on writing great answers.

Post Your Answer Discard

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged c++ vector or ask your own question.


site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev2021.11.12.40742

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.