Reputation: 5611
I don't know C++, but need to make some adjustments to some code I have inherited. One part of the code has:
array<vector<string>, 2> names;
I am now trying to print the contents of each vector in this array. How do I go about doing that?
I know I can iterate over one vector like this:
for (unsigned int p=0; p<vector.size(); p++)
cout << vector.at(p) << endl;
I can not figure out how to adjust this to print the contents of each vector in the array though.
Thank you for any help you can provide. I'm out of my element here.
Upvotes: 0
Views: 1046
Reputation: 16253
One-line solution (not necessarily preferable in this case because manually iterating with for
as in Rapptz' answer is easier to read, but still nice to know):
std::for_each(names.begin(), names.end(), [](vector<string>& v){
std::copy(v.begin(),v.end(),
std::ostream_iterator<string>(std::cout,"\n")});
Upvotes: 0
Reputation: 21317
In C++11 you can iterate through this pretty easily.
for(auto& i : names) {
for(auto& k : i) {
std::cout << k << std::endl;
}
}
Upvotes: 2
Reputation: 45410
Just like iterate through vector, you need to iterate through array:
for (int i=0; i<2; i++)
{
for (unsigned int p=0; p<names[i].size(); p++)
{
cout << names[i].at(p) << endl;
}
}
Or
for (auto it = std::begin(names); it != std::end(names); ++it)
{
for (unsigned int p=0; p<(*it).size(); p++)
{
cout << (*it).at(p) << endl;
}
}
Upvotes: 0
Reputation: 2084
Using iterators:
array<vector<string>,2> names;
for (array<vector<string>,2>::iterator i=names.begin();i!=names.end();i++)
{
for (vector<string>::iterator j=i->begin();j!=i->end();j++)
{
cout << *j << endl;
}
}
Upvotes: 0