ashim
ashim

Reputation: 25590

c++, creating vector of vectors?

Question is about what is the best way to create vector of vectors. I have several vector<double> coordinates; and I want pass them to function. How I should combine them, vector<vector<double> >? Is there more elegant way?

Upvotes: 2

Views: 6749

Answers (4)

Remy Lebeau
Remy Lebeau

Reputation: 598299

Another option woud be to put the vectors into an array and pass that to the function, eg:

void foo(std::vector<double> **vecs, int numVecs)
{
   ...
}

int main() 
{  
    std::vector<double> coordinates1, coordinates2, coordinates3; 
    //... 

    std::vector<double>* CoordinateVectors[3]; 
    CoordinateVectors[0] = &coordinates1; 
    CoordinateVectors[1] = &coordinates2; 
    CoordinateVectors[2] = &coordinates3; 

    foo(CoordinateVectors, 3); 

    return 0; 
} 

Or:

void foo(std::vector<double> *vecs, int numVecs)
{
   ...
}

int main() 
{  
    std::vector<double> coordinates[3]; 
    //... 

    foo(coordinates, 3); 

    return 0; 
} 

Upvotes: 0

Oliver Charlesworth
Oliver Charlesworth

Reputation: 272802

That sounds like a reasonable approach. If you're worried about readability, then use a typedef.

However, if all of your vectors are the same length (e.g. you're really trying to create a 2D array), then consider using a boost::multi_array.

Upvotes: 3

marcinj
marcinj

Reputation: 50036

Maybe something like that:

typedef vector<double> coords_vec_type;
typedef vector<coords_vec_type> coords_vec2_type;

void foo(coords_vec2_type& param) {
}

or with pointers to avoid copying if source vectors are at some place already:

typedef vector<coords_vec_type*> coords_vec2_ptr_type;

Upvotes: 1

Igor
Igor

Reputation: 27268

Just like you said looks fine:

void foo(vector<vector<double> > &);

int main()
{ 
    vector<double> coordinates1, coordinates2, coordinates3;
    //...

    vector<vector<double> > CoordinateVectors;
    CoordinateVectors.push_back(coordinates1);
    CoordinateVectors.push_back(coordinates2);
    CoordinateVectors.push_back(coordinates3);

    foo(CoordinateVectors);

    return 0;
}

Upvotes: 1

Related Questions