Create constant sized vector of constant sized vectors - c++

I am trying to learn C++. Currently I ran into a tutorial, which mentioned how to create a constant sized vector like this: vector <int> v(10); Now I'm wondering how to create a constant sized vector of constant sized vectors, something like: vector <vector <int> (10)> v(10); This code doesn't work, so I wanted to ask is there a way do something like this and if there is, how?

You could
vector<vector<int>> v(10, vector<int>(10));
i.e. construct the std::vector with 10 copies of elements with value std::vector<int>(10).
Note that for std::vector the size is not constant, it might be changed when element(s) are inserted or erased, 10 is just the initial size when v and its elements get initialized. On the other hand, the size of std::array is constant, it's specified at compile-time and can't be changed at run-time.

You can't have a constant sized vector of constant sized vectors without writing your own class wrapper of some kind. Use the more appropriate std::array container for the task:
std::array<std::array<int, 10>, 10> arr;

Related

Initializing an array of vector

I am trying to initialize an array of a vector of ints.
This is my code:
vector<int> *vec[] = new vector<int>[n+1];
I get the following compilation error:
initialization with '{...}' expected for aggregate object
What's wrong with this ?
If you need an array (in the broad sense) of elements of type vector<int>, I advise you to use:
std::vector<std::vector<int>> vec(n+1);
vec will be a vector of vectors. The number of vectors will be n+1 like it seems you wanted. std::vector will manage the memory for you, so there's no need for new/delete.
In C++ we also have std::array, but it looks like the number of elements in vec is dynamically dependant on n, which makes a topmost std::vector the proper fit.
There are many advantages using C++ std::vector/std::array over C style arrays. See e.g. the answers here: std::vector versus std::array in C++.
If you must use a C style topmost array, see the other answer.
The problem is that you're trying to initialize an array of pointers to vector with a "pointer to a vector".
To solve this you can either remove the [] from the left hand side of the declaration or not mix std::vector and raw pointers.
//--------------v----------------------->removed [] from here
vector<int> *vec = new vector<int>[n+1];

What is the difference in the vector<int> vec[n] and vector<vector<int>> vec in C++?

I just started learning graphs data structure and came through the adjacency matrix and adjacency lists.
The Adjacency list use vector<int> vec[n], where n is the number of vertices.
But I think that the working of vector<int> vec[n] i.e so-called adjacency list is same as the vector of vectors...i.e vector<vector<int>> vec.
Please help me out with this!
Let's start simple:
int arr[n];
std::vector<int> vec;
arr is a C array of ints. This data type is very bare bone. You can't easily get its size and lacks all of the modern OOP features. It has a lot of other problems e.g.:
in most contexts it decays to pointer
the return type cannot be array
you can't have array type as function parameter - what looks like a C array type is in fact a pointer type
vec is a proper C++ container representing a dynamic vector. You can access its size, you can grow it, shrink it etc.
Don't use C arrays. Use standard containers. std::vector should be the first choice. If the size is known at compile time and it doesn't change use std::array instead.
vector<int> vec[n]
Is a freakish Frankenstein's monster. It's a C array of vectors of ints.
is same as the vector of vectors...i.e vector<vector<int>> vec
Close. The C++ equivalent would be std::array<std::vector<int>, n>.
Note: there are some compilers (most notably gcc and clang) that accept n as a non constant size for a C array (the so called Variable Length Arrays), but that isn't standard and portable.
Both are not equivalent
std::vector<int> vec[n];
declares an fixed size array of size n where n must be known at compile time (or a compiler extension must be available). During the initialization of vec the constructors of all n vectors are called. These vectors are allocated on the stack.
std::vector<std::vector<int>> vec;
creates an empty vector of vectors though. The constructor of std::vector<int> is never called. You need to call
vec.resize(n);
to change the size of vec to n calling the constructors of std::vector<int> n times. In contrast to std::vector<int> vec[n]; n does not need to be a compile time constant with this approach. Furthermore you can apply other operations on a std::vector<std::vector<int>> changing the number of elements further.
In the second version the std::vector<int> objects are allocated on the heap. (The elements of the std::vector<int>s are stored different locations on the heap.)
In this declaration
std::vector<int> vec[n];
there is declared an array. You can not resize the array for example removing or adding new elements.
On the other hand, using this declaration
std::vector<std::vector<int>> vec( n );
you can resize the vector removing or adding new elements.
Another problem is that arrays do not have the assignment operator.
Also arrays do not have comparison operators.
vector<int> vec[n];
is an array (a so called C-Style array) of size n with elements of type vector<int>
vec can't grow / shrink in size, however it's elements can (.resize(), .push_back(), .pop_back())
vector<vector<int>> vec;
is a two dimensional vector of type int
vec can grow / shrink to any size, and it's element can do so as well.
which one is better? For your case the vector<vector<int>> probably, but it really depends on the use, C-Style arrays require you know the size before, but can be more optimized as the memory will be on the stack. For example, if you know the size of the matrix beforehand, you can use a pure 2d C-Style array:
int matrix[n][m];
With C-Style arrays you loose the size when passed to a function, so std::array is preferred here, they are as optimized and come with utilities such as .size(), .back() etc:
std::array<std::array<int, m>, n> matrix;

Query regarding initialization of a vector in c++

I was trying the vector implementation in C++ stl and couldn't figure out what exactly does this mean:
vector< int > vec[N]
If we simply write int a[10],it's an array of 10 elements. Doesn't the same logic apply to vectors as well?
Isn't it a vector of arrays containing N elements each.Also,when I tried the .size() function on vec it gave an error" error: request for member ‘size’ in ‘vec’, which is of non-class type ‘std::vector [3]'"(Considering N=3)
Please correct me if I misunderstood the concept.
Thanks
Vector is a template class, with array as underlying data structure. Although you don't need to assign size to a vector because it increases its size dynamically, but you may want to reserve space to it while declaring. You can do it by "std::vector< int> vec(size)".
Your syntax actually seems an array of vector of int type, and not a vector of arrays.

array of vectors or vector of arrays?

I'm new to C++ STL, and I'm having trouble comprehending the graph representation.
vector<int> adj[N];
So does this create an array of type vector or does this create a vector of arrays? The BFS code seems to traverse through a list of values present at each instance of adj[i], and hence it seems works like an array of vectors.
Syntax for creating a vector is:
vector<int> F;
which would effectively create a single dimensional vector F.
What is the difference between
vector< vector<int> > N;
and
vector<int> F[N]
So does this (vector<int> adj[N];) create an array of type vector or does this create a
vector of arrays?
It creates array of vectors
What is the difference between
vector< vector<int> > N;
and
vector<int> F[N]
In the first case you are creating a dynamic array of dynamic arrays (vector of vectors). The size of each vector could be changed at the run-time and all objects will be allocated on the heap.
In the second case you are creating a fixed-size array of vectors. You have to define N at compile-time, and all vectors will be placed on the stack†, however, each vector will allocate elements on the heap.
I'd always prefer vector of vectors case (or the matrix, if you could use third-party libraries), or std::array of std::arrays in case of compile-time sizes.
I'm new to C++ STL, and I'm having trouble comprehending the graph
representation.
You may also represent graph as a std::unordered_map<vertex_type,std::unordered_set<vertex_type>>, where vertex_type is the type of vertex (int in your case). This approach could be used in order to reduce memory usage when the number of edges isn't huge.
†: To be precise - not always on stack - it may be a part of a complex object on the heap. Moreover, C++ standard does not define any requirements for stack or heap, it provides only requirements for storage duration, such as automatic, static, thread or dynamic.
Short Answer:
It's an array of vector <int>s.
Long Answer:
When reading a declaration such as
vector<int> adj[N];
The compiler uses a method known as the "spiral-" or "clockwise-rule" in order to interpret what it means. The idea behind the spiral rule is that you start at the variable name, and move outwards in a clockwise spiral in order to figure out what type of variable it is. For example:
char* str [10];
Can be interpreted like this:
____
| |
char* str [10];
|_________|
Making str an array of 10 char*s.
Therefore, vector<int> adj[N]; is an array of vectors rather than a vector of arrays
Practice makes perfect:
1: What does int * foo [ ]; mean?
Answer:
"foo" is an array of pointers to integers
2: What does int * (*foo [ ] )(); mean?
Answer:
"foo" is an array of pointers to functions returning pointers to integers
3: What does int * (*(*foo [ ] )())(); mean?
Answer:
"foo" is an array of pointers to functions returning pointers to functions returning pointers to integers
vector<int> arr[N];
It displays an array of vector, each array[i] would have a vector stored in it that can traverse through many values. It is like a an Array of Linked List where the heads are only stored in array[i] positions.
vector<vector<int> > N vs vector<int> F[N]
The difference between 2D Vector and an Array of Vector is that 2D Vectors can span in size while array of vectors have their dimension fixed for the array size.
Under the hood a vector still uses array, it is implementation specific but is safe to think that:
vector<int>
internally creates an int[].
What vectors gives you is that it abstract from you the part where if you want to re-size you don't have to re-allocate manually etc, it does that for you (plus much more of course).
When you do: vector<vector<int>> you are going to create a vector of vectors, meaning a 2D matrix. You can nest it as much as you want.
Vector takes in a type T and allocates an array of that type. so if you pass vector as type T, it will effectively do what you did in your first line, an array of vector<int>.
Hope it makes sense

How to initialize an array of vector<int> in C++ with predefined counts?

Excuse me, I'm new in STL in C++. How can I initialize an array of 10 vector pointer each of which points to a vector of 5 int elements.
My code snippet is as follows:
vector<int>* neighbors = new vector<int>(5)[10]; // Error
Thanks
This creates a vector containing 10 vector<int>, each one of those with 5 elements:
std::vector<std::vector<int>> v(10, std::vector<int>(5));
Note that if the size of the outer container is fixed, you might want to use an std::array instead. Note the initialization is more verbose:
std::array<std::vector<int>, 10> v{{std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5),
std::vector<int>(5)
}};
Also note that the contents of array are part of the array. It's size, as given by sizeof, is larger than the vector version, and there is no O(1) move or swap operation available. An std::array is akin to a fixed size, automatic storage plain array.
Note also that, as #chris suggests in the comments, you can chose to set the elements of the array after a default initialization, e.g. with std::fill if they are all to have the same value:
std::array<std::vector<int>, 10> v; // default construction
std::fill(v.begin(), v.end(), std::vector<int>(5));
otherwise, you can set/modify the individual elements:
v[0] = std::vector<int>(5); // replace default constructed vector with size 5 one
v[1].resize(42); // resize default constructed vector to 42
and so on.