istream_iterator + double vector
-
Meet the problem when the flow-through elements are introduced
istream_operator<int>
♪ Knowledge comes more than necessary.If there's any advice on improving the quality of the code, I'll just be grateful. Here's the code:
#include <iostream> #include <vector> #include <iterator> #include <algorithm> using namespace std;
int main() {
vector<vector<int>> price;
unsigned int n = 0;
cin>>n;
price.reserve(n);
for (int i = 0 ; i < n; i++)
{
vector<int> vec(2,0);
price.push_back(vec);
}
for (int i = 0; i < n ; i++)
{
for (int j = 0; j < 2;j++)
{
istream_iterator<int> in(cin);
price[i][j] = *in;
++in;
}
}
for (int i = 0; i < n ; i++)
{
ostream_iterator<int> out(cout," ");
for (int j = 0; j < 2;j++)
{
copy(price[i].begin(),price[i].begin()+n,out);
}
}
return 0;
}
-
You have this cycle.
for (int i = 0; i < n ; i++) { ostream_iterator<int> out(cout," "); for (int j = 0; j < 2;j++) { copy(price[i].begin(),price[i].begin()+n,out); } }
Uncorrect.
That's right.
for ( int i = 0; i < n ; i++) { ostream_iterator<int> out( cout, " " ); copy( price[i].begin(), price[i].end(), out ); }
Or
ostream_iterator<int> out( cout, " " ); for ( int i = 0; i < n ; i++) { copy( price[i].begin(), price[i].end(), out ); }
Or
ostream_iterator<int> out( cout, " " ); for ( vector<vector<int>>::size_type i = 0; i < price.size() ; i++) { copy( price[i].begin(), price[i].end(), out ); }
You mean you're all in the same line, not in the form of a matrix.
It would be easier to write.
for ( const auto &row : price ) { for ( auto x : row ) std::cout << x << ' '; std::cout << std::endl; }
But it looks like you want to practice with the terator. :
Also instead of this fragment, the code
vector<vector<int>> price; unsigned int n = 0; cin>>n; price.reserve(n); for (int i = 0 ; i < n; i++) { vector<int> vec(2,0); price.push_back(vec); }
You could write that down.
unsigned int n = 0; cin>>n;
vector<vector<int>> price( n, vector<int>( 2 ) );
In these cycles, the definition of the inlet may be outwards.
istream_iterator<int> in(cin);
for (int i = 0; i < n ; i++)
{
for (int j = 0; j < 2;j++)
{
price[i][j] = *in;
++in;
}
}
Of course it would be easier not to use the terator, but to write it simply.
for (int i = 0; i < n ; i++)
{
for (int j = 0; j < 2;j++)
{
cin >> price[i][j];
}
}