【发布时间】:2018-11-07 05:14:45
【问题描述】:
我正在尝试创建一个设置大小的二维向量,然后将数据插入其中。我遇到的问题是能够插入填充二维向量中每一列和每一行的数据。
我已经阅读了各种其他线程,但找不到适合我的实现。
这是我的问题的一些示例代码:
int main()
{
vector<string> strVec = { "a","b","c","d" };
// letters to insert into vector
// this is just a sample case
vector< vector<string>> vec; // 2d vector
int cols = 2; // number of columns
int rows = 2; // number of rows
for (int j = 0; j < cols; j++) // inner vec
{
vector<string>temp; // create a temporary vec
for (int o = 0; o < rows; o++) // outer vec
{
temp.push_back("x"); // insert temporary value
}
vec.push_back(temp); // push back temp vec into 2d vec
}
// change each value in the 2d vector to one
// in the vector of strings
// (this doesn't work)
// it only changes the values to the last value of the
// vector of strings
for (auto &v : strVec)
{
for (int i = 0; i < vec.size(); i++)
{
for (int j = 0; j < vec[i].size(); j++)
{
vec[i][j] = v;
}
}
}
// print 2d vec
for (int i = 0; i < vec.size(); i++)
{
for (int j = 0; j < vec[i].size(); j++)
{
cout << vec[i][j];
}
cout << endl;
}
}
【问题讨论】:
-
要将
vec预设为2 行2 列,请将vector< vector<string>> vec;更改为vector< vector<string>> vec(2, vector<string>(2));。现在您可以使用vec[i][j]而无需退回。 That said, here's a better alternative。因为只有一个vector,所以所有数据都紧密地打包在一起,极大地提高了缓存的友好性和分配存储所花费的时间。