Putting vectors in vector

Hello,
I would like to use for loop to create vectors in my main vector. I would like the first vector to be of length of 1 another of length of 2 and the 'n' vector of length of n.
MainVec(Length: n = 4)
/\"Small" vectors
|--->(L: 4)
|-->(L: 3)
|->(2)
|>(1)
1
2
3
4
5
6
7
  	long n;
	std:cin << n;
	std::vector<long> MainVec (n,0);
	for( long y = 0; y < n; y ++ )
	{
            MainVec[y] = std::vector<long> SmallVec (y+1,0);
	}

Is my code in any way correct?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <vector>

int main ()
{
    std::size_t n ;
    std::cin >> n ;

    std::vector< std::vector<long> > main_vec(n) ; // vector of vectors
    for( std::size_t i = 0 ; i < n ; ++i ) main_vec[i].resize(i+1) ;

    for( const auto& row : main_vec )
    {
        for( long v : row ) std::cout << v << ' ' ;
        std::cout << '\n' ;
    }
}

http://coliru.stacked-crooked.com/a/e09ee7a4c1aca357
Really thanks for you reply. Still Im newbie at those things :(
1
2
3
4
5
6
   
 for( const auto& row : main_vec )
    {
        for( long v : row ) std::cout << v << ' ' ;
        std::cout << '\n' ;
    }

I dont understand :(
Whats const auto&?
why there is ":" in for loop?
Why do we use size_t?
> Whats const auto&?

auto: http://www.stroustrup.com/C++11FAQ.html#auto
In this case, the type is deduced to be std::vector<long> - the type of the values that the outer vector contains.
Ergo, const auto&: reference to const std::vector<long>.


> why there is ":" in for loop?
It is a range-based for loop: http://www.stroustrup.com/C++11FAQ.html#for

Both are language features that came with C++11.


> Why do we use size_t

http://www.cplusplus.com/reference/cstddef/size_t/
The ":" is part of the syntax of range-based for. That variant of for was added by the C++11 update of C++ standard.

auto in C++11 does mean "same type as the value_type of main_vec". The other bits say that 'row' is a const reference; they narrow down the 'auto'.

size_t is an unsigned integral type. Just the type that vector's operator[] expects.
Topic archived. No new replies allowed.