[英]Push back data into a 2D vector
我正在尝试创建一个设置大小的二维矢量,然后将数据插入其中。 我遇到的问题是能够插入填充2d向量中每列和每行的数据。
我已经阅读了各种其他线程,但找不到适合我的实现。
以下是我的问题的一些示例代码:
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;
}
}
您在for (auto &v : strVec)
的循环中一次又一次地为vec
所有元素分配相同的字符串。 也就是说, vec[0][0]=vec[0][1]=vec[1][0]=vec[1][1]=a
, vec[0][0]=vec[0][1]=vec[1][0]=vec[1][1]=b
,依此类推。
删除此外部循环并将strVec[i*cols+j]
分配给vec[i][j]
,我们可以获得所需的输出。
for (int i = 0; i < vec.size(); i++)
{
for (int j = 0; j < vec[i].size(); j++)
{
vec[i][j] = strVec[i*cols+j];
}
}
for (int i = 0; i < vec.size(); i++)
{
for (int j = 0; j < 2; j++)
{
cout << vec[i][j];
}
cout << endl;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.