【问题标题】:why vector resize its size when i take input same element in the vecotor为什么当我在向量中输入相同的元素时向量会调整其大小
【发布时间】:2021-06-18 15:53:31
【问题描述】:

//这里如果我输入 n=5 然后插入 vec1 1,2,3,4, 5 然后根据其大小在输出中仅考虑 1,2,3,4但是当我尝试在 vec1 1,2,2,2,3,4 中插入时,它的 输出 是 1,2,2,2,3,4 how?因为它的 size 是 4。

#include<bits/stdc++.h>
using namespace std;

int main(){
    int n;
    cin>>n;
    vector<int> vec1;
    for (int i=0; i<n; ++i){
        cin>>i;
        vec1.push_back(i);
    }
    sort(vec1.begin(), vec1.end());
    vector<int> :: iterator it;
    for( it = vec1.begin(); it !=vec1.end(); it++)
        cout<<*it<<" ";
        cout<<vec1.size();

}

【问题讨论】:

    标签: c++ vector size


    【解决方案1】:

    cin&gt;&gt;i 将覆盖您的循环变量(因此循环在您输入一个数字 &gt;= n - 1 后终止)。

    您需要使用不同的变量来获取您的输入。

    int x;
    cin >> x;
    vec1.push_back(x);
    

    【讨论】:

      猜你喜欢
      • 2016-12-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-05
      • 2015-04-25
      • 2018-05-02
      • 1970-01-01
      • 2020-04-01
      相关资源
      最近更新 更多