[英]Is there multiple ways to cin vector elements?
I have a program that adds multiple vectors in 1 vector.我有一个程序可以在 1 个向量中添加多个向量。 I saw a method of instead of.push_back to add elements and I used it, but I am wondering why this works because I thought vector[] indicated the index, so why is cin >> vector[] adding elements into the vector if square brackets indicate the index?
我看到了一种方法 instead of.push_back 添加元素并使用了它,但我想知道为什么这有效,因为我认为 vector[] 表示索引,那么为什么 cin >> vector[] 将元素添加到 vector if square括号表示索引? input - output 1 2;
输入 - output 1 2; 5 4;
5 4; 9 1 - 1 2;
9 1 - 1 2; 5 4;
5 4; 9 1
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)
makes a vector q2
that has 2 default-constructed int
elements in it. vector<int> q2(2)
生成一个向量q2
,其中包含 2 个默认构造的int
元素。 You don't need to push_back()
elements, because it makes 2 elements for you when it is constructed.您不需要
push_back()
元素,因为它在构造时会为您生成 2 个元素。
cin >> q2[b]
merely edits the int
elements that already exist in the vector. 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.