I defined an empty vector of vectors :
vector< vector<int> > v;
How do i fill that empty vector with vector of size 2 integers ( from input ) each iteration of while loop?
while ( cin >> x >> y ) {
//....
}
Will this one work? Or what's the best and most elegant / effective way of doing it?
while ( cin >> x >> y )
{
vector<int> row;
row.push_back( x );
row.push_back( y );
v.push_back( row );
}
As pointed out by JerryCoffin, you probably better use a :
struct Point {
int x;
int y;
};
and then you might overload the output operator
std::ostream& operator<< (std::ostream& o,const Point& xy){
o << xy.x << " " << xy.y;
return o;
}
and similar the input operator (see eg here ). And then you can use it like this:
int main() {
Point xy;
std::vector<Point> v;
v.push_back(xy);
std::cout << v[0] << std::endl;
return 0;
}
The another way of doing so is to push the value in a 1-D vector and then push that 1-D vector in 2-D vector. I have also printed the values as a test.
#include<bits/stdc++.h>
using namespace std;
int main()
{
int t,n,temp;
cin>>t;
vector<vector<int>> value;
for(int i=0;i<t;i++)
{
cin>>n;
vector<int> x;
for(int j=0;j<n;j++)
{
cin>>temp;
x.push_back(temp);
}
value.push_back(x);
}
for(int i=0;i<t;i++)
{
for(int j=0;j<value[i].size();j++)
{
cout<<value[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
Hope it helps!!
I wrote it - compilator didnt say anything but i have never used vectors so i haven't figured out how to print it yet
You can print using for example a range based for loop (C++11):
for (const auto &vec : v) { // for every vector in v
for (const auto &num : vec) // print the numbers
cout << num << " ";
cout << '\n';
}
And regular for loop:
for (unsigned int i = 0; i != v.size(); ++i) {
for (unsigned int j = 0; j != v[i].size(); ++j) {
cout << v[i][j] << " ";
}
cout << '\n';
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.