【问题标题】:C++ Vector and cin [duplicate]C ++向量和cin [重复]
【发布时间】:2020-09-20 04:36:15
【问题描述】:
#include <iostream>
#include<vector>

using namespace std;

int main() {

    int n,k;
    cin>>n;
    cin>>k;

    vector<int> arr(n);
    int temp;
    for(int i=0;i<n;i++){
        cin>>temp;
        arr.push_back(temp);                                                                
    }
    for(int i=0;i<n;i++){
        cout<<arr[i]<<" ";
    }
    
    return 0;
}

为什么元素不存储到向量中?怎么回事?

输入:
6 3
1 2 3 4 5 6

输出:
0 0 0 0 0 0

【问题讨论】:

  • 试试这个#include。添加它。
  • @Mr.Perfectist #include&lt;bits/stdc++.h&gt; 是一种不好的做法,问题在给定的链接中得到了回答
  • 输入:6 3 1 2 3 4 5 6 输出:0 0 0 0 0 0
  • 你的问题有很多答案!!也看到这个stackoverflow.com/questions/63875203/…
  • @asmmo 明白了..谢谢

标签: c++ vector


【解决方案1】:

试试这个改变:

for(int i=0;i<n;i++){
    cin>>temp;
    arr[i] = temp; // here is the change
}

为什么 OP 的代码不起作用?

vector&lt;int&gt; arr(n); 创建了一个由n 元素组成的向量。 arr.push_back(temp); 导致n 更多元素的推送。 因此,如果您打印 2n 长度,您可以看到您的答案。

for(int i=0;i< 2*n;i++){ // here is the change.
    cout<<arr[i]<<" ";
}

对于输入 2 2 3 4,可以得到输出 0 0 3 4。

您应该将这些输入 temp 设置为已分配的内存,而不是推送更多的元素 n

或者,只是push,而不是预先分配内存。 而不是 vector&lt;int&gt; arr(n); 声明为 vector&lt;int&gt; arr; 它应该可以工作。

【讨论】:

  • 我知道这样做或其他方式。但问题是为什么它不起作用?
  • @Nirajsingh:编辑帖子以回答您的问题。
  • 为什么读入一个临时变量而不是直接读入向量元素?
  • @AlanBirtles:我只是想尽可能多地保留与 OP 相似的代码。 OP 的代码可能还有更多改进,但我想坚持提出的问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-20
  • 1970-01-01
  • 2021-04-11
  • 2018-10-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多