Pro*_*OXO 3 c++ arrays syntax vector push-back
我正在尝试定义'row'或1D向量的值,然后将该行push_back到2D向量中.我尝试了几个不会抛出错误而且似乎也无法正常工作的不同东西.代码如下:
#include <vector>
#include <iostream>
using std::vector;
#define HEIGHT 5
#define WIDTH 3
// 2D VECTOR ARRAY EXAMPLE
int main() {
vector<vector<double> > array2D;
vector<double> currentRow;
// Set up sizes. (HEIGHT x WIDTH)
// 2D resize
array2D.resize(HEIGHT);
for (int i = 0; i < HEIGHT; ++i)
{
array2D[i].resize(WIDTH);
}
// Try putting some values in
array2D[1][2] = 6.0; // this works
array2D[2].push_back(45); // this value doesn't appear in vector output. Why?
// 1D resize
currentRow.resize(3);
// Insert values into row
currentRow[0] = 1;
currentRow[1] = 12.76;
currentRow[2] = 3;
// Push row into 2D array
array2D.push_back(currentRow); // this row doesn't appear in value output. Why?
// Output all values
for (int i = 0; i < HEIGHT; ++i)
{
for (int j = 0; j < WIDTH; ++j)
{
std::cout << array2D[i][j] << '\t';
}
std::cout << std::endl;
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)
当你push_back currentRow时,array2D已经包含HEIGHT行,而在push_back之后它将包含HEIGHT + 1行.您只是不显示您添加的最后一个,只显示第一个HEIGHT行.
| 归档时间: |
|
| 查看次数: |
4787 次 |
| 最近记录: |