Basic Problem Can you please help me understand how to use a vector of a vector. Take for example vector< vector<int> > help. I do not understand if it is a vector of ints who each are a vector of ints or if it is a vector of a vector of ints? I also don't understand how to utilize it.
Example Code
vector< vector<int> > test[500];
test[0].emplace_back(1);
cout << test[0][0];
test[50].emplace_back(4);
cout << " " <<test[50][0];
-console-
1 50 //this is not what happens btw, but it is the desired results
Disclaimer I have spent the better part of a morning testing and googling this. Please help :) I did my hw. I can't find any documentation of vectors of a vector. Also I have all the correct libraries and I am using namespace std. I am a noob and i understand that namespaces are bad practice, but its very convient for me right now.
Basically what I want is a set size of a vector filled with each pt being a vector of int. I would rather not go the way of a separate class. Is a vector of a vector of int, the right thing to be looking into?
Thank you :)
This is a vector of int:
std::vector<int> v;
this is a vector of vectors of int:
std::vector<std::vector<int>> v2;
this is an array of vectors of vectors of ints, which is what you have:
std::vector<std::vector<int>> test[500];
each element of that array is an std::vector<std::vector<int>>. So test[0] is one of those.
If you want a vector of 500 default constructed vectors of int, you need
std::vector<std::vector<int>> test(500);
test is an array of 500 vectors of vectors of int. The second line of your example should not even compile here, as you are calling std::vector< std::vector<int> >::emplace_back(), which expects an argument compatible with std::vector<int>, and you have provided an int. To clarify:
test is a std::vector< std::vector<int> >[500].
test[0] is a std::vector< std::vector<int> >.
test[0][0] is a std::vector<int>.
test[0][0][0] is an int.
(Pedantic C++ developers will note that the latter three are actually references, but I'm omitting that from the type for clarity.)
A vector is just a resizable array.
To declare a vector of int (an array of int), just do:
std::vector<int> vec;
To declare a array in which individual elements are vectors, you do:
std::vector< std::vector<int> > vecarr;
To set the initial size of the vector, you do:
std::vector<int> vec(500); not std::vector<int> vec[500], because this creates an array of 500 std::vectors. Similarly, std::vector< std::vector<int> > vec[500]; creates a array of 500 vector of vectors.
To skip writing std:: you can say using namespace std before all this to tell that you're using the std namespace.
What you have there is an array of vector-of-vector which I believe since you're accessing the data with two indexes is not what you wanted.
I believe you may have just typo-ed your constructor initialization:
vector< vector<int> > test(500); // Note () instead of [] here.
This creates a vector-of-vectors, with 500 inner vectors pre-created for you. Then the rest of your code should just work!
Related
I'm making socoban game in C++ now. I'd like to know how can I make a pointer array which can contains multidimensional vectors.
For example,
I created some 2-demension vectors
vector<vector<char> > vector1;
vector<vector<char> > vector2;
I want to make a pointer
For example (pointer)[0] = &vector1
like this
Please tell me how.
I'm trying to pass a variable of type vector<vector<double> > to a function F(double ** mat, int m, int n). The F function comes from another lib so I have no option of changing it. Can someone give me some hints on this? Thanks.
vector<vector<double>> and double** are quite different types. But it is possible to feed this function with the help of another vector that stores some double pointers:
#include <vector>
void your_function(double** mat, int m, int n) {}
int main() {
std::vector<std::vector<double>> thing = ...;
std::vector<double*> ptrs;
for (auto& vec : thing) {
// ^ very important to avoid `vec` being
// a temporary copy of a `thing` element.
ptrs.push_back(vec.data());
}
your_function(ptrs.data(), thing.size(), thing[0].size());
}
One of the reasons this works is because std::vector guarantees that all the elements are stored consecutivly in memory.
If possible, consider changing the signature of your function. Usually, matrices are layed out linearly in memory. This means, accessing a matrix element can be done with some base pointer p of type double* for the top left coefficient and some computed linear index based on row and columns like p[row*row_step+col*col_step] where row_step and col_step are layout-dependent offsets. The standard library doesn't really offer any help with these sorts of data structures. But you could try using Boost's multi_array or GSL's multi_span to help with this.
The way I see it, you need to convert your vector<vector<double> > to the correct data type, copying all the values into a nested array in the process
A vector is organised in a completely different way than an array, so even if you could force the data types to match, it still wouldn't work.
Unfortunately, my C++ experience lies a couple of years back, so I can't give you a concrete example here.
Vector< Vector< double> > is not nearly the same as a double pointer to m. From the looks of it, m is assumed to be a 2-dimensional array while the vector is could be stored jagged and is not necessarily adjacent in memory. If you want to pass it in, you need to copy the vector values into a temp 2dim double array as pass that value in instead.
Vector Vector C ++
Hi, I do not understand the syntax of nested vectors to simulate an array, I have the following code.
vector< vector< float> > myvector (n, vector < float> (2));
But I do not quite understand how it works, especially where you specify the size of the vectors and the vectors in it, if you want to make a resize so that my vector vector has specified dimensions how can I resize internal vectors?
Something like changing vec [10] [2] to vec [10] [5] (changing the second dimension)
In addition to how to make copies with multidimensional vectors something like:
vector< int> myvector (myVectorToCopy, myVectorToCopy+myVectorToCopy.size());
But with several dimensions.
Thanks.
vector<vector<float>> means you are creating a vector which contains a vector of floats. The constructor argument means you are creating a vector of size n where each element of vector is a vector of floats having size 2.
To resize the vector<vector<float>>:
for (int i = 0; i < n; ++i)
A[i].resize(newSize);
Alternatively you could use:
A.assign(n,vector<float>(newSize));
To make a copy of multidimensional vector use constructor:
vector<vector<float>> B(A);
Vectors in C++ will resize automatically if you fill them up and try to add more to them. If you know the exact size of your vector, I would suggest switching to std::array, however you will lose the ability to resize them at runtime.
std::vector::operator[] has an overload to return a reference to the T used to create the template (in your case T is std::vector, the nested one). If you know the index in the outer vector, you could do something like:
myVec[0].resize(5);
This will resize your nested vector at position 0 to 5 elements.
Copying is much the same as accessing:
std::copy(std::begin(VecToCopy), std::end(VecToCopy), std::begin(VecToFill));
Using std::begin last might not be what you want but its just an example.
http://en.cppreference.com/w/cpp/algorithm/copy
http://en.cppreference.com/w/cpp/container/array
vector <int> V[] and vector< vector<int> > V both are 2D arrays.
But what is the difference between them and where do we use each one? Please give a brief explanation.
vector<int> V[] is an array of vectors.
vector< vector<int> > V is a vector of vectors.
Using arrays are C-style coding, using vectors are C++-style coding.
Quoting cplusplus.com ,
Vectors are sequence containers representing arrays that can change in
size.
Just like arrays, vectors use contiguous storage locations for their
elements, which means that their elements can also be accessed using
offsets on regular pointers to its elements, and just as efficiently
as in arrays. But unlike arrays, their size can change dynamically,
with their storage being handled automatically by the container.
TL;DR:
When you want to work with a fixed number of std::vector elements, you can use vector <int> V[].
When you want to work with a dynamic array of std::vector, you can use vector< vector<int> > V.
One difference would be that although both can be initialized in the same way, e.g.
vector<int> V1[] {{1,2,3}, {4,5,6}};
vector<vector<int>> V2 {{1,2,3}, {4,5,6}};
and accessed
cout << V1[0].back() << endl;
cout << V2[0].back() << endl;
the V1 can't grow. You cannot make V1.push_back(...) as its not a vector object. Its just an array. Second one is dynamic. You can grow it as you please.
vector<vector<int>> v(26); is a vector containing vectors. In this example, you have a vector with 26 vectors contained in it. The code v[1].push_back(x) means that x is pushed back to the first vector within the vectors.
vector<int> a[26]; is an array of vectors. In other words, a one-dimensional array containing 26 vectors of integers. The code a[1].push_back(x); has x being pushed back to the first index of the array.
vector<int> v[] is an array of vectors. That is, it is an array which contains vectors as its elements.
So, you cannot change the size of the array part, but we can add to its elements which is vector.
For example,
1.vector<int> v1[] = {{1},{2},{3}}; // array that contains 3 vector elements.
2.vector<vector<int>> v2 = {{1},{2},{3}}; // vector that contains 3 vector elements.
So for the first we cannot change the size of v but we can add or delete elements to its elements since it is a vector.
v1.push_back(4); // this will give an error since we cannot the predefined size of array.
v1[1].push_back(4); // this is acceptable since we are changing the vector part.
This makes the v1 {{1},{2,4},{3}}
For the second one, we can change both the overall size and its elements.
v2.push_back(4); // this is acceptable since it is vector.
vector V[] is just a fixed array; and so you can add/modify only till the upper limit. It is not a vector per se, and so has a fixed size limit.
However vector< vector > V is a dynamic vector and its size can be increased dynamically.
I was trying to copy an int array into std::vector of int and I am seeing some unusual behavior. So I have an array as defined as below.
int myarray[10] = {1,2,3,4,5,6,7,8,9,10};
and I tried copying the above array into vector using different methods as below which throws errors.
1) Using reserve
std::vector<int> vec1;
vec1.reserve(10);
std::copy(myarray, myarray+10,vec1.begin() );
This throws an error in VS 2013 which is :-
vector iterator + offset out of range
2) By defining size
std::vector<int> vec2(10);
std::copy(myarray, myarray+10,vec2.begin() );
Which successfully copies the array into the vector.
3) Just declaring the vector .
std::vector<int> vec3;
std::copy(myarray, myarray+10,vec3.begin() );
Which also throws an error
vector iterator + offset out of range
Also searching over the internet I found that std::back_inserter could be used, but I don't know what difference it would make.
Can some please explain the difference between all the three methods and whats going wrong in 1 and 3.
Instead of vec1.reserve(10); use vec1.resize(10);
std::vector::reserve would increase the capacity of vector but the size remains same. It requests that the vector capacity be at least enough to contain n elements.
On the other hand, std::vector::resize resizes the container so that it contains n elements
As #Mohit Jain's answer shows resize would help. But that initializes the vector which is not needed. For integers it might not be a problem but for big objects it's definitely a performance overhead.
reserve can help here if you use std::copy as shown below.
std::vector<int> vec2(10);
vec2.reserve(10);
std::copy(myarray, myarray+10, std::back_inserter(vec));
BTW, you can also copy the contents of the array to the vector during the construction of the vector itself.
std::vector<int> vec2 ( myarray, myarray + 10);