两个向量<string>串联

two vector<string> concatenation

本文关键字:lt gt 串联 string 向量 两个      更新时间:2023-10-16

我有两个向量,像这样:

A ={"Sam", "Jordan", "Mike"}
B ={"Smith", "Lancaster", "Horgen"}

串联后,它们应如下所示:

A ={"SamSmith", "JordanLancaster", "MikeHorgen"}

基本上,您将名字和姓氏组合在一起。我该怎么做?

使用std::transform(实时示例):

std::transform(
    begin(A), end(A), begin(B), begin(A), 
    [](const auto& s1, const auto& s2) { return s1 + s2; }
);
for (size_t i = 0; i < A.size() && i < B.size(); ++i)
   A[i] += B[i];

现在,A向量包含所需的输出。

它可以通过迭代两个向量并在每一步中concatenating字符串并将结果重新分配给A来轻松完成,

 typedef vector<string>::iterator VIter;
    for(VIter it1=A.begin(), it2=B.begin(); it1 != A.end(), it2 != B.end(); ++it1, ++it2)
    {
            *it1 = *it1 +*it2;
    }