Stack Overflow Asked by 2Kbummer on December 20, 2021
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;
}
}
'''
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.
Answered by Mooing Duck on December 20, 2021
Get help from others!
Recent Questions
Recent Answers
© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP