Reputation: 73
I'm having trouble understanding why my array of vectors is not inputting a line. ...
#include<bits/stdc++.h>
using namespace std;
int main () {
int r;
cin>>r;
vector <int> v[r];
for (int i=0; i<r; i++) {
for (int j=0; j<i; j++) {
int x;
cin>>x;
v[i].push_back(x);
}
}
for (int i=0; i<r; i++) {
for (size_t j=0; j<v[i].size(); j++){
cout<<v[i][j];
}
cout<<endl;
}
}
... With input ...
5
7
3 8
8 1 0
2 7 4 4
4 5 2 6 5
... it outputs ...
7
38
810
2744
... with an empty line in the beginning of the output.
Upvotes: 0
Views: 59
Reputation: 1288
The issue is just in one line (commented on the body of code below). Also I changed your code to be more c++ alike.
//#include<bits/stdc++.h> //Include all libraries is a bad practice. Include just what you need
#include <vector>
#include <iostream>
using namespace std;
int main () {
int r;
cin >> r;
vector<vector<int>> v(r, vector<int>()); //more secure than c-style vector<int> v[r]
//and create the 1st level of vector
for (int i = 0; i < r; ++i)
for (int j = 0; j < i; ++j) { //Here is the issue
v[i].emplace_back();
cin >> v[i].back();
}
for (auto& i : v) { //Iterate over the 1st level of vector
for (auto& j : i) //Iterate over the 2nd level of vector
cout << j << ' ';
cout << '\n';
}
return 0;
}
Upvotes: 0
Reputation: 1413
You saw empty line at the beginning of output, because v[0]
was empty. You can fix it this way:
#include<bits/stdc++.h>
using namespace std;
int main () {
int r;
cin>>r;
// vector <int> v[r];
// ^
// This is variable length array which is not really legal in C++. Use:
vector<vector<int>> v;
v.resize(r);
for (int i=0; i<r; i++) {
for (int j=0; j<=i; j++) {
// ^^
// This loop had 0 iterations when i == 0, 1 when i == 1, ..., 4 when i == 4.
// So you need to do one more iteration each time.
int x;
cin>>x;
v[i].push_back(x);
}
}
for (int i=0; i<r; i++) {
for (size_t j=0; j<v[i].size(); j++){
cout<<v[i][j];
}
cout<<endl;
}
}
Also:
bits/stdc++.h
is bad: Why should I not #include <bits/stdc++.h>?, you should include only what you need:#include <iostream>
#include <vector>
using namespace std
is bad: Why is "using namespace std;" considered bad practice?.Upvotes: 2