为什么输出中有0?

huangapple go评论86阅读模式
英文:

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 vectors in it and then pushing 2 populated vectors 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&lt;vector&lt;int&gt; &gt;a;
a.reserve(2);
...
vector&lt;int&gt; b;
b.reserve(m); 

Otherwise, if you do use the constructor to pre-fill the vectors with defaults, then
you need to change your loops to use vector::operator[] instead of vector::push_back(), eg:

vector&lt;vector&lt;int&gt; &gt;a(2);
for(int i=0;i&lt;2;i++)
{
    ... 
    vector&lt;int&gt; b(m);

    for(int j=0;j&lt;m;j++)
    {
        ...
        b[j] = k;
    } 

    a[i] = b;
} 

huangapple
  • 本文由 发表于 2023年6月22日 10:19:21
  • 转载请务必保留本文链接:https://go.coder-hub.com/76528218.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定