简体   繁体   中英

C++ print contents of array of string vectors?

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.

In C++11 you can iterate through this pretty easily.

for(auto& i : names) {
    for(auto& k : i) {
        std::cout << k << std::endl;
    }
}

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;
   }
 }

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;
  }
}

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")});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM