0

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.

4

4 回答 4

2

在 C++11 中,你可以很容易地遍历它。

for(auto& i : names) {
    for(auto& k : i) {
        std::cout << k << std::endl;
    }
}
于 2013-02-14T04:07:58.200 回答
0

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;
  }
}
于 2013-02-14T04:00:15.133 回答
0

单行解决方案(在这种情况下不一定可取,因为for在 Rapptz 的答案中手动迭代更容易阅读,但仍然很高兴知道):

std::for_each(names.begin(), names.end(), [](vector<string>& v){
              std::copy(v.begin(),v.end(),
                        std::ostream_iterator<string>(std::cout,"\n")});
于 2013-02-14T04:13:09.833 回答
0

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;
   }
 }
于 2013-02-14T03:59:15.430 回答