'Is there multiple ways to cin vector elements?
I have a program that adds multiple vectors in 1 vector. 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? input - 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;
}
}
'''
Solution 1:[1]
vector<int> q2(2)
makes a vector q2
that has 2 default-constructed int
elements in it. You don't need to push_back()
elements, because it makes 2 elements for you when it is constructed.
cin >> q2[b]
merely edits the int
elements that already exist in the vector.
Solution 2:[2]
#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;
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Remy Lebeau |
Solution 2 | Rivendharan |