Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Pointers Dilemma

Tags:

c++

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):

  • ONE is an array of three std::vector objects (all of them are being initialized using the default constructor, I guess)
  • 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.

  • FOUR is a pointer to the first of three std::vector pointers.

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 :)

like image 535
Matteo Pacini Avatar asked Apr 30 '26 13:04

Matteo Pacini


1 Answers

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;
}
like image 84
πάντα ῥεῖ Avatar answered May 03 '26 02:05

πάντα ῥεῖ