[英]Is there multiple ways to cin vector elements?
我有一個程序可以在 1 個向量中添加多個向量。 我看到了一種方法 instead of.push_back 添加元素並使用了它,但我想知道為什么這有效,因為我認為 vector[] 表示索引,那么為什么 cin >> vector[] 將元素添加到 vector if square括號表示索引? 輸入 - output 1 2; 5 4; 9 1 - 1 2; 5 4; 9 1
'''
#include <vector>
#include <iostream>
using namespace std;
int main()
{
int q = 3; //total number of q2 in q1
vector<vector<int>> q1; //vector for q2's
for(int a = 0; a < q; a++)
{
vector<int> q2(2); //making each q2 vector the size of 2 elements
for(int b = 0; b < 2; b++){
cin >> q2[b]; //adding elements to q2**how does this work instead of push_back?
}
q1.push_back(q2); //adding last q2 into q1
}
//printing q1
for(int a = 0; a < q1.size(); a++){
for(int b = 0; b < q1[a].size(); b++){
cout << q1[a][b] << " ";
}
cout << endl;
}
}
'''
vector<int> q2(2)
生成一個向量q2
,其中包含 2 個默認構造的int
元素。 您不需要push_back()
元素,因為它在構造時會為您生成 2 個元素。
cin >> q2[b]
僅編輯向量中已經存在的int
元素。
#include<iostream>
#include<vector>
using namespace std;
double meannum(vector <double> &listnum);
int main()
{
double dum {0.0};
vector <double> listnum {};
cout << "Enter the list of numbers to find the mean: press any non-integer key to stop"<<endl;
while (cin >> dum) //enter any non-integer to end the loop!
{
listnum.push_back(dum);
}
cout << "List of numbers entered : "<< endl ;
for(int i = 0;i < listnum.size();i++) {
cout << listnum.at(i) << endl;
}
cout << " Finding the mean ..... " << endl;
cout << "result: " << meannum(listnum);
}
double meannum(vector<double> &listnum)
{
int len = listnum.size();
double sum{ 0 };
for (int i = 0; i < len; i++) {
sum = sum + listnum.at(i);
}
double avg = sum / len;
return avg;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.