C++,创建向量的向量

c++, creating vector of vectors?

本文关键字:向量 创建 C++      更新时间:2023-10-16

问题是关于创建vector vector的最佳方法是什么。我有几个vector<double> coordinates;,我想让它们发挥作用。vector<vector<double> >,我应该如何组合它们?还有比这更优雅的方式吗?

这听起来像是一个合理的方法。 如果您担心可读性,请使用typedef

但是,如果所有向量都是相同的长度(例如,您确实在尝试创建 2D 数组(,请考虑使用 boost::multi_array

就像你说的看起来不错:

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

也许是这样的:

typedef vector<double> coords_vec_type;
typedef vector<coords_vec_type> coords_vec2_type;
void foo(coords_vec2_type& param) {
}

或者使用指针来避免复制,如果源向量已经在某个地方:

typedef vector<coords_vec_type*> coords_vec2_ptr_type;

另一种选择是将向量放入数组并将其传递给函数,例如:

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

或:

void foo(std::vector<double> *vecs, int numVecs)
{
   ...
}
int main() 
{  
    std::vector<double> coordinates[3]; 
    //... 
    foo(coordinates, 3); 
    return 0; 
}