繁体   English   中英

如何让我的向量在输入后显示 8 个整数? 当我输入 8 个整数时,它只显示零而不是我输入的内容

[英]How do I get my vector to display 8 integers after entering them? When I do enter 8 integers, it only displays zeros and not what I entered

#include <iostream>
#include <vector>

using namespace std;

int main() {
    int val = 8;
    vector<int>numVal(val);
    unsigned int i;

    cout << "Enter " << val << " integers: "<< endl;
    for(i = 0; i < numVal.size(); i++) 
    {
        cin >> val;
    }

   cout << "Congratulations! You entered 8 integers." << endl;

   for(i = 0; i < numVal.size(); i++)
   {
       cout << numVal.at(i)<<" ";
   }  

   return 0;
}

您使用 8 个默认值元素初始化vector ,然后完全忽略用户的输入。 这就是你打印零的原因。

您需要通过以下方式将用户的输入存储在vector中:

  • 使用vectoroperator[]访问预先分配的元素:
#include <iostream>
#include <vector>

using namespace std;

int main() {
    vector<int> numVal(8);
    size_t i;

    cout << "Enter " << numVal.size() << " integers: "<< endl;
    for(i = 0; i < numVal.size(); i++) 
    {
        cin >> numVal[i];
    }

   cout << "Congratulations! You entered " << numVal.size() << " integers." << endl;

   for(i = 0; i < numVal.size(); i++)
   {
       cout << numVal[i] << " ";
   }  

   return 0;
}
  • 不是预先填充vector的元素,而是使用它的push_back()方法:
#include <iostream>
#include <vector>

using namespace std;

int main() {
    int val;
    vector<int> numVal;
    size_t i;

    numVal.reserve(8);

    cout << "Enter " << numVal.capacity() << " integers: "<< endl;
    for(i = 0; i < numVal.capacity(); i++) 
    {
        cin >> val;
        numVal.push_back(val);
    }

   cout << "Congratulations! You entered " << numVal.size() << " integers." << endl;

   for(i = 0; i < numVal.size(); i++)
   {
       cout << numVal[i] << " ";
   }  

   return 0;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM