[英]why can't I store values in my 2D vector by push back?
I got stuck in many problems where I was trying to store values in 2D vectors. 我陷入了很多问题,试图在2D向量中存储值。 So I have written this simple code. 所以我写了这个简单的代码。
I am just storing and printing my values : 我只是存储和打印我的价值观:
int main()
{
vector<vector<int>> vec;
vector<int> row{1,3,5,7,9,12,34,56};
int i,n,m,rs,vs;
rs=row.size();
cout<<"rs = "<<rs<<endl;
for(i=0;i<(rs/2);i++)
{
vec[i].push_back(row.at(i));
vec[i].push_back(row.at(i+4));
}
vs=vec.size();
cout<<vs<<endl;
for(n=0;n<vs;n++)
{
for(m=0;m<2;m++)
{
cout<<vec[n][m]<<" ";
}
cout<<endl;
}
return 0;
}
First you should read Why is “using namespace std;” considered bad practice? 首先,您应该阅读为什么“使用命名空间标准”被认为是不好的做法? . 。
Declare variables when you use them and not at the beginning of your program. 在使用变量时而不是在程序开始时声明变量。
The vector vec
is empty at the beginning. 向量vec
开头是空的。 In the loop 在循环
for(i=0;i<(rs/2);i++)
{
vec[i].push_back(row.at(i));
vec[i].push_back(row.at(i+4));
}
you are taking a reference to the i-th element in vec
with 您正在使用vec
的第i个元素进行引用
vec[i]
but this element does not exist. 但是此元素不存在。 This is undefined behavior and can result in a segmentation fault. 这是未定义的行为,可能会导致分段错误。 You can fix it by constructing the vector with the needed elements 您可以通过使用所需元素构建向量来修复它
#include <iostream>
#include <vector>
int main()
{
std::vector<int> row{1,3,5,7,9,12,34,56};
int rs = row.size();
std::vector<std::vector<int>> vec(rs / 2);
std::cout << "rs = " << rs << '\n';
for(int i = 0; i < rs / 2; ++i)
{
vec[i].push_back(row.at(i));
vec[i].push_back(row.at(i + 4));
}
int vs = vec.size();
std::cout << vs << '\n';
for(int n = 0; n < vs; ++n)
{
for(int m = 0; m < 2; ++m)
{
std::cout << vec[n][m] << " ";
}
std::cout << '\n';
}
return 0;
}
In this example the line 在这个例子中
std::vector<std::vector<int>> vec(rs / 2);
constructs a vector containing rs / 2
default constructed elements. 构造一个包含rs / 2
默认构造元素的向量。 Alternatively you can start with an empty vector and push back elements in the loop 或者,您可以从空向量开始,然后在循环中推回元素
#include <iostream>
#include <vector>
int main()
{
std::vector<int> row{1,3,5,7,9,12,34,56};
int rs=row.size();
std::vector<std::vector<int>> vec;
std::cout << "rs = " << rs << '\n';
for(int i = 0; i < rs / 2; ++i)
{
vec.push_back({row.at(i), row.at(i+4)});
//
// is similar to:
// vec.push_back({});
// vec.back().push_back(row.at(i));
// vec.back().push_back(row.at(i+4));
//
// is similar to:
// vec.push_back({});
// vec[i].push_back(row.at(i));
// vec[i].push_back(row.at(i+4));
}
int vs = vec.size();
std::cout << vs << '\n';
for(int n = 0; n < vs; ++n)
{
for(int m = 0; m < 2; ++m)
{
std::cout << vec[n][m] << " ";
}
std::cout << '\n';
}
return 0;
}
I recommend the first solution. 我建议第一个解决方案。 It's better to allocate memory for all elements and work with it instead of allocate memory in each loop iteration. 最好为所有元素分配内存并使用它,而不是在每个循环迭代中分配内存。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.