Как я могу объединить два элемента в одной позиции двух разных векторов? - PullRequest
0 голосов
/ 23 февраля 2020

введите 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 - входные данные)

Ответы [ 2 ]

1 голос
/ 23 февраля 2020

Вы можете перебрать оба вектора и просто добавить строку в 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
0 голосов
/ 23 февраля 2020
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;
}
...