vector<vector<int>> sort_a;
vector<int> v2;
vector<int> v3;
for (int i=0; i<4; ++i) {
v2.push_back(i);
for (int j=0; j<4; ++j) {
v3.push_back(j);
sort_a.push_back(v2);
sort_a.push_back(v3);
}
}
Run Code Online (Sandbox Code Playgroud)
矢量sort_a应该是一个4x4数组,而输出是31x1,有很多空元素,我如何在多维向量中插入元素?
不要将它视为多维向量,将其视为向量的向量.
int n = 4;
std::vector<std::vector<int>> vec(n, std::vector<int>(n));
// looping through outer vector vec
for (int i = 0; i < n; i++) {
// looping through inner vector vec[i]
for (int j = 0; j < n; j++) {
(vec[i])[j] = i*n + j;
}
}
Run Code Online (Sandbox Code Playgroud)
我将括号括在(vec[i])[j]了理解之中.
编辑:
如果你想通过填充向量push_back,可以在内部循环中创建一个临时向量,填充它,然后将其推送到向量:
for (int i = 0; i < n; i++) {
std::vector<int> temp_vec;
for (int j = 0; j < n; j++) {
temp_vec.push_back(j);
}
vec.push_back(temp_vec);
}
Run Code Online (Sandbox Code Playgroud)
但是,push_back调用会导致代码变慢,因为您不仅需要始终重新分配矢量,还需要创建临时代码并进行复制.
avector<vector<int>>不是多维存储的最佳实现。以下植入对我有用。
template<typename T>
class array_2d {
std::size_t data;
std::size_t col_max;
std::size_t row_max;
std::vector<T> a;
public:
array_2d(std::size_t col, std::size_t row)
: data(col*row), col_max(col), row_max(row), a(data)
{}
T& operator()(std::size_t col, std::size_t row) {
assert(col_max > col && row_max > row)
return a[col_max*col + row];
}
};
Run Code Online (Sandbox Code Playgroud)
用例:
array_2d<int> a(2,2);
a(0,0) = 1;
cout << a(0,0) << endl;
Run Code Online (Sandbox Code Playgroud)
该解决方案与此处描述的解决方案类似。
| 归档时间: |
|
| 查看次数: |
20610 次 |
| 最近记录: |