如何将两个不同矢量的同一位置的两个元素组合在一起

How can I combine two elements in the same position of two different vectors?

本文关键字:两个 位置 元素 组合 在一起      更新时间:2023-10-16

输入v1和v2得到v3,例如,

v1 = {"abcd", "sfc", "fec"}
v2 = {"Chengdu","Chongqing","Shanghai"}
v3 = {"abcdChengdu","sfcChongqing", "fecShanghai"}

另一个例子,

v1 = {"xc", "sj"}
v2 = {"sd","gv","md"}
v3 = {"xcsd","sjgv","md"}

并且其他示例可以以相同的方式进行。如何获得v3?(请记住,将v1和v2作为输入(

您可以对两个向量进行迭代,只需将v1中的字符串+v2中的字符串添加到一个新向量中:

#include <algorithm>
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>
std::vector<std::string> comb(const std::vector<std::string>& a,
const std::vector<std::string>& b) {
std::vector<std::string> result;
// get a reference to the smallest vector and to the largest vector
const auto minmaxpair = std::minmax(a, b,
[](const auto& A, const auto& B) {
return A.size() < B.size();
}
);
auto& min = minmaxpair.first;
auto& max = minmaxpair.second;
// reserve space for a result as big as the larger vector
result.reserve(max.size());
// add as many entries as there are in the smaller vector
size_t idx = 0;
for(; idx < min.size(); ++idx)
result.emplace_back(a[idx] + b[idx]);
// add the rest from the larger vector
for(; idx < max.size(); ++idx) 
result.push_back(max[idx]);
return result;
}
int main() {
std::vector<std::string> v1 = {"xc", "sj"};
std::vector<std::string> v2 = {"sd", "gv", "md"};
auto v3 = comb(v1, v2);
for(auto& s : v3) std::cout << s << 'n';
}

输出:

xcsd
sjgv
md
auto combine(const std::vector<std::string>& v1, const std::vector<std::string>& v2){ // asserting that v1 and v2 have the same length
std::vector<std::string> v3 {};
for(auto i = 0 ; i < std::min(v1.size(), v2.size()); ++i) v3.push_back(v1[i] + v2[i]);
if(v1.size() < v2.size())
for(auto i = v1.size() ; i < v2.size(); ++i) 
v3.push_back(v2[i]);
else if(v1.size() > v2.size())
for(auto i = v2.size() ; i < v1.size(); ++i)
v3.push_back(v1[i]);
return v3;
}