简体   繁体   中英

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

input v1 and v2 to get v3, For example,

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

Another more example,

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

and other examples can be done the same way. How can I get v3? (DO REMEMBER take v1 and v2 as inputs)

You could iterate over both vectors and just add the string in v1 + the string in v2 to a new vector:

#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';
}

Output:

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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