Reputation: 825
I have this code so far: #include "std_lib_facilities_4.h"
void numbers()
{
vector<int> first;
vector<int> second;
vector<int> third;
vector<int> fourth;
vector< <vector<data> > all;
for (int i = 0; i <= 9; ++i)
{
first.push_back(i);
second.push_back(i);
third.push_back(i);
fourth.push_back(i);
}
all.push_back(first);
all.push_back(second);
all.push_back(third);
all.push_back(fourth);
cout << all[0] << '\n';
cout << all[1] << '\n';
cout << all[2] << '\n';
cout << all[3] << '\n';
}
int main()
{
numbers();
}
How do I create a vector 'all' made up of the vectors 'first', 'second', 'third', and 'fourth'?
Upvotes: 0
Views: 369
Reputation: 310980
It is not clear what you want. Whether you want to define a vector of vectors or place all elements of all four vectors in one vector.
If you want to do the first task then it can be done the following way
void numbers()
{
vector<int> first;
vector<int> second;
vector<int> third;
vector<int> fourth;
for ( int i = 0; i <= 9; ++i )
{
first.push_back(i);
second.push_back(i);
third.push_back(i);
fourth.push_back(i);
}
std::vector<std::vector<int>> all( { first, second, third, fourth } );
for ( const std::vector<int> &v : all )
{
for ( int x : v ) std::cout << x << ' ';
std::cout << std::endl;
}
}
If you want to create one vector from all elements of other four vectors then the function can look the following way
void numbers()
{
vector<int> first;
vector<int> second;
vector<int> third;
vector<int> fourth;
for ( int i = 0; i <= 9; ++i )
{
first.push_back(i);
second.push_back(i);
third.push_back(i);
fourth.push_back(i);
}
std::vector<int> all = first;
all.insert( all.back(), second.begin(), second.end() );
all.insert( all.back(), third.begin(), third.end() );
all.insert( all.back(), fourth.begin(), fourth.end() );
for ( int x : all ) std::cout << x << ' ';
std::cout << std::endl;
}
Upvotes: 0
Reputation: 49986
you actually have a vector of vectors, whats wrong with your all
vector? You have other problems with your code:
I assume your data is something like:
typedef int data;
you have small typo here:
vector< <vector<data> > all;
^---- remove it!
this is wrong:
cout << all[0] << '\n';
cout << all[1] << '\n';
cout << all[2] << '\n';
cout << all[3] << '\n';
you should iterate each sub vector like that to output all elements:
for (auto t : all[0])
cout << t << ',';
Upvotes: 2
Reputation: 3255
Simple. Just do the following:
vector <vector <int> > group
Or for readability purposes you can typedef vector <vector <int> > BigVector
and then initialize as follows:
BigVector group
You can use the push_back()
member function but supply a vector <int>
as your argument.
Upvotes: 2