0

I made a vector of vectors and i wanted to take values from the user.I simply don't know what is the problem with it

why can't i use push_back() here and if you have any other method than this please tell.

vector<vector<int>>  v;
for(int i=0;i<n;i++)
{
   v.push_back(i+1);
   for(int j=0;j<n;j++)
    {
        v[i].push_back(j+1);
    }
}

doing this gives me error

error: no matching function for call to 'std::vector<std::vector<int> >::push_back(int)'
v.push_back(i+1);
3
  • 5
    What are you trying to achieve by this statement v.push_back(i+1);? Commented Feb 20, 2021 at 16:59
  • 2
    The vector v doesn't contain ints, so you can not push back an int in line 4. You could for example pushback an empty vector, or your can use resize before the loop. Commented Feb 20, 2021 at 17:00
  • thanks sir,i completely understood the point now. Commented Feb 20, 2021 at 17:12

3 Answers 3

1

You declared a vector of vectors of the type std::vector<std::vector<int>>.

vector<vector<int>>  v;

It means that elements of the vector v has the type std::vector<int> not int.

So the compiler issues an error message for this statement

v.push_back(i+1);

that does not make a sense.

You could use such a call provided that the class template std::vector had an implicit constrictor from an integer expression to the type std::vector. However such a constructor is explicit

explicit vector(size_type n, const Allocator& = Allocator());

Thus there is no implicit conversion from the parameter an expression supplied to the parameter n to the type std::vector<int>.

It seems you mean the following

vector<vector<int>>  v;
for(int i=0;i<n;i++)
{
   v.resize(i+1);
   for(int j=0;j<n;j++)
    {
        v[i].push_back(j+1);
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Regarding v.resize(i+1) - just vector<vector<int>> v(n); for crying out loud.
0

It is because v is a vector containing a vector of ints. Meaning you can't push_back an integer as it wants an int vector.

vector<vector<int>>  v;
for(int i=0;i<n;i++)
{
    vector<int> v2;
    for(int j=0;j<n;j++)
    {
        v2.push_back(j+1);
    }
    v.push_back(v2);
}

Now consider this code, it will work because you are creating a new vector of ints, v2. If you push v2 to v, it will work as v requires an int vector for push_back.

Comments

0

People like to overcomplicate things when answering. The idea here is that you have created a vector inside a vector. So the first vector takes a vector as an input, whereas the second vector takes an "int". Therefore, you shouldn't push an integer in the first vector but a VECTOR of integers.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.