简体   繁体   English

C ++打印字符串向量数组的内容?

[英]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. 我不懂C ++,但需要对我继承的一些代码做一些调整。 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. 在C ++ 11中,您可以非常轻松地迭代它。

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): 一号线的解决方案(在这种情况下,并不一定可取,因为与手动迭代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")});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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