c++, creating vector of vectors?

醉酒当歌 提交于 2019-12-22 18:29:17

问题


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?


回答1:


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.




回答2:


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;
}



回答3:


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;



回答4:


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; 
} 


来源:https://stackoverflow.com/questions/8660303/c-creating-vector-of-vectors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!