[英]C++ print contents of array of string vectors?
我不懂C ++,但需要對我繼承的一些代碼做一些調整。 代碼的一部分有:
array<vector<string>, 2> names;
我現在正在嘗試打印此數組中每個向量的內容。 我該怎么做呢?
我知道我可以像這樣迭代一個向量:
for (unsigned int p=0; p<vector.size(); p++)
cout << vector.at(p) << endl;
我無法弄清楚如何調整它來打印數組中每個向量的內容。
感謝您提供任何幫助。 我不在這里。
在C ++ 11中,您可以非常輕松地迭代它。
for(auto& i : names) {
for(auto& k : i) {
std::cout << k << std::endl;
}
}
就像迭代向量一樣,你需要遍歷數組:
for (int i=0; i<2; i++)
{
for (unsigned int p=0; p<names[i].size(); p++)
{
cout << names[i].at(p) << endl;
}
}
要么
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;
}
}
使用迭代器:
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;
}
}
一號線的解決方案(在這種情況下,並不一定可取,因為與手動迭代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.