Home c++ "vector subscript out of range" error in loop

“vector subscript out of range” error in loop




code [1]

On compilation, (1) produces (2). What to do? How to fight?

Answer 1, authority 100%

You cannot apply an indexing operator to a vector that has no elements yet.

Therefore, you should write before the loops

cin & gt; & gt; str;
cin & gt; & gt; stb;
vect.resize (str, std :: vector & lt; int & gt; (stb));

That is, you first need to create the elements of the vector, and then only access them by index.

Answer 2

As a variant of initialization (when creating, you can specify the dimension):

int a, b;
cin & gt; & gt; a & gt; & gt; b;
vector & lt; vector & lt; int & gt; & gt; mas (a, vector & lt; int & gt; (b));
size_t size = mas.size ();
for (size_t i = 0; i & lt; size; ++ i) {
  for_each (mas [i] .begin (), mas [i] .end (), [] (int & amp; k) {cin & gt; & gt; k;});
Previous articlePhp curl + https
Next articleIs there a FSIS USRR API?

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions