Vector of vectors - why doesn't this work

So suppose I want a vector of vector<int>'s, and fill up position [0][0] with the number 5.

Here's the code for that:

1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <vector>

int main()
{
    std::vector<std::vector<int> > v; // create a vector of vectors
    v.push_back(std::vector<int>()); // push anonymous vector<int> object into
                                     // 'outer' vector
    v[0].push_back(5);  // now we can use [] operator to push 5 into 0th index 
                                  // of 'outer' vector
    
    std::cout << v[0][0]; // prints 5, as expected
}


Above code works fine. Now I try to shorten my code a little by doing the following:

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
#include <vector>

int main()
{
    std::vector<std::vector<int> > v;
    v.push_back(std::vector<int>().push_back(5)); // use push_back directly on 
                                              // anonymous vector object
    
    std::cout << v[0][0];
}


This doesn't compile but I expected it to. Why not?
Last edited on
The type of the expression std::vector<int>().push_back(5) is void
Topic archived. No new replies allowed.