[英]c++, creating vector of vectors?
問題是,什么是創造最好的辦法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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.