繁体   English   中英

使用迭代器连接向量中的元素

[英]using iterator to concatenate elements in a vector

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

现场例子

using namespace std;

auto it_first = begin(myVec);
auto it_last = begin(myVec) + 2;
while (it_last != end(myVec)) 
    for_each(it_first, it_last++, [](string const & str) { cout << str << " "; });
    cout << endl;
}

这应该做。 编辑:已纠正的错误:)应该给您正确的输出,请确认。 接下来还有一个额外的内容。

这样的事情,如果可以使用boost

 std::vector<std::string> s { "bob", "hey", "joe", "doe" };
 std::vector<std::string> d;

 for (auto i = std::begin(s); i != std::end(s); ++i) {
     d.push_back(boost::algorithm::join(
         boost::make_iterator_range(std::begin(s), i + 1), 
         std::string(" ")
     ));
 }

输出向量d将包含以下内容:

bob
bob hey
bob hey joe
bob hey joe doe

但是更有效的解决方案是使用临时字符串:

 std::vector<std::string> s { "bob", "hey", "joe", "doe" };
 std::vector<std::string> d;

 std::string t;
 std::for_each(std::begin(s), std::end(s), [&](const std::string &i) {
     d.push_back(t += (i + " "));
 });

您可以使用与cout完全相同的方式使用stringstream。 它们会保存在字符串中,而不是打印到屏幕上。 可以使用.str()访问该字符串。

请参见: 如何使用C ++字符串流附加int?

您的代码如下所示:

vector <int> myVec;
std::stringstream ss;

for(int i=0; i<10; i++)  
    myVec.push_back(i);  //vector holding 0-9

vector<int>::iterator it;
for(it=myVec.begin(); it!=myVec.end(); ++it) {
    ss<<*it<<endl;
    cout << ss.str() << " ";   // prints 1 12 123 1234 ...
}

// ss.str() == "123456789";

您可以尝试使用std::string + operatoriterator进行合并,如下所示

std::string myCompleteString;
vector<std::string>::iterator it;
for(it=myVec.begin(); it!=myVec.end(); ++it)
        myCompleteString  += *it +  " ";

cout << myCompleteString;

暂无
暂无

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

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