将数据推回二维向量
Push back data into a 2D vector
我正在尝试创建一个设定大小的二维向量,然后将数据插入其中。我遇到的问题是能够插入填充二维向量中每一列和每一行的数据。
我已经通读了其他各种线程,但找不到适合我的实现。
这是我的问题的一些示例代码:
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;
}
我正在尝试创建一个设定大小的二维向量,然后将数据插入其中。我遇到的问题是能够插入填充二维向量中每一列和每一行的数据。
我已经通读了其他各种线程,但找不到适合我的实现。
这是我的问题的一些示例代码:
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;
}