c++ - 使用迭代器连接 vector 中的元素

标签 c++ vector iterator

string s1 = "bob"; 
string s2 = "hey";
string s3 = "joe";
string s4 = "doe";

vector<string> myVec;

myVec.push_back(s1);
myVec.push_back(s2);
myVec.push_back(s3);
myVec.push_back(s4);

如何在 myVec 上使用迭代器输出“bob hey”“bob hey joe”“bob hey joe doe”?

任何帮助提示或帮助将不胜感激

最佳答案

以下应该有效:

for (auto it = myVec.begin(), end = myVec.end(); it != end; ++it)
{
    for (auto it2 = myVec.begin(); it2 != (it + 1); ++it2)
    {  
        std::cout << *it2 << " ";
    }
    std::cout << "\n";
}

示例输出:

bob 
bob hey 
bob hey joe 
bob hey joe doe

Live Example

关于c++ - 使用迭代器连接 vector 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22124894/

相关文章:

c++ - C++ 中的 COM 事件处理

c++ - static_cast<int>(var) 和 *(int*)&var 有什么区别?

c++ - 删除动态分配的 vector 会清除它的内容吗

java - 如何在迭代时从 "ConcurrentModificationException"中删除元素时避免 `ArrayList` ?

c++ - iterator 和 const_iterator 之间的比较是否效率低下?

java - 是否有理由使用字符串 => 索引到 vector 的映射,而不是字符串 => 对象?

c++ - "Guaranteed Delivery"消息传递 - 我应该使用 MQTT 还是 ZeroMQ?

c++ - 这段代码有什么问题?

c++ - 如何将 std::transform 与带有附加参数的 lambda 函数一起使用

python - 为什么我不能对相同的数据进行两次迭代?