英文:
Why 0 is in the output?
问题
在输出中为什么会出现零?
输出应该没有零。
在第二个 push_back
函数中,如果我使用 b[j]
,那么零就不会出现。
英文:
#include <cmath>
#include <cstdio>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
vector<vector<int> >a(2);
for(int i=0;i<2;i++)
{
int m;
cout<<"Enter number of elements on the row:"<<endl;
cin>>m;
vector<int> b(m);
cout<<"Element:"<<endl;
for(int j=0;j<m;j++)
{
int k;
cin>>k;
b.push_back(k)//if i use b[j]=k; here the zeros don't appear.
//cout<<b[j];
}
a.push_back(b);
}
for(unsigned int i=0;i<a.size();i++)
{
for(unsigned int j=0;j<a[i].size();j++)
cout<<a[i][j]<<" ";
cout<<endl;
}
return 0;
}
Why does zero appear in the output?
The output should be without zeros.
In the second push_back
function, if I use b[j]
then zeros don't appear.
答案1
得分: 5
你正在用两个空的vector
初始化a
,然后将两个填充了数据的vector
推入其中。
而对于b
,你正在用m
个默认的零值初始化,然后将m
个用户输入的整数推入其中。
你不应该在构造函数中为任何一个vector
初始化数值。这会将默认值推入vector
,从而影响你的结果。在这种情况下,只需删除构造函数中的值,让push_back()
来处理添加操作。
如果你想要在不添加值的情况下预分配vector
的内存,可以使用它的reserve()
方法,例如:
vector<vector<int>> a;
a.reserve(2);
...
vector<int> b;
b.reserve(m);
否则,如果你确实使用构造函数来填充vector
的默认值,那么你需要修改循环以使用vector::operator[]
而不是vector::push_back()
,例如:
vector<vector<int>> a(2);
for(int i=0; i<2; i++)
{
...
vector<int> b(m);
for(int j=0; j<m; j++)
{
...
b[j] = k;
}
a[i] = b;
}
英文:
You are initializing a
with 2 blank vector
s in it and then pushing 2 populated vector
s into it.
And you are initializing b
with m
number of default zeros and then pushing m
user-input integers into it.
You should not be initializing either vector
with a value in its constructor. That pushes default values into the vector
, which is throwing off your results. In this case, simply remove the constructor values and let push_back()
handle the adds for you.
If you want to preallocate a vector
's memory without adding values to it, use its reserve()
method instead, eg:
vector<vector<int> >a;
a.reserve(2);
...
vector<int> b;
b.reserve(m);
Otherwise, if you do use the constructor to pre-fill the vector
s with defaults, then
you need to change your loops to use vector::operator[]
instead of vector::push_back()
, eg:
vector<vector<int> >a(2);
for(int i=0;i<2;i++)
{
...
vector<int> b(m);
for(int j=0;j<m;j++)
{
...
b[j] = k;
}
a[i] = b;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论