I have been playing with pointers in C++ for the last few hours.
Then I got stuck on this...
vector<int> one[3];
vector<int>* two[3];
vector<vector<int> > three(3);
vector<int>** four = new vector<int>*[3];
I would like to create an array(or a vector) that contains 3 vectors of integers.
What I think I know (correct me if I'm wrong):
TWO is an array of three std::vector pointers. It means that I have to dynamically alloc the three pointers, like this:
two[0] = new vector<int>();
two[1] = new vector<int>();
two[2] = new vector<int>();
THREE is a vector that contains three std::vector initialized objects.
Which is the best way to achieve that (and why?)
UPDATE:
This is the the output of LLDB when I print those variables.
http://pastebin.com/raw.php?i=JLyeB4uK
It doesn't sound right...
Code is:
//METHOD ONE:
vector<int> one[3];
//METHOD TWO:
vector<int>* two[3];
two[0] = new vector<int>();
two[1] = new vector<int>();
two[2] = new vector<int>();
//METHOD THREE:
vector<vector<int> > three(3);
//METHOD FOUR:
vector<int>** four = new vector<int>*[3];
four[0] = new vector<int>();
four[1] = new vector<int>();
four[2] = new vector<int>();
Thanks :)
I would like to create an array(or a vector) that contains 3 vectors of integers
std::array<std::vector<int>,3> myThreeVectors;
would be the best choice IMHO.
Unfortunately this isn't available for pre-c++11 standard. As a surrogate you could best use the simple c-style array (any decent c++ compiler should be able to handle the class instantiations of plain array elements correctly):
std::vector<int> myThreeVectors[3] = { };
which is equivalent to
std::vector<int> myThreeVectors[3] =
{ std::vector<int>()
, std::vector<int>()
, std::vector<int>()
};
Here's a running sample:
#include <iostream>
#include <vector>
using namespace std; // Don't use this in headers
std::vector<int> myThreeVectors[3] = { };
int main() {
for(int i = 0; i < 3; ++i)
{
cout << "myThreeVectors[" << i << "].size() = " <<
myThreeVectors[i].size() << endl;
}
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With