我如何连接两个std::向量?


当前回答

vector<int> v1 = {1, 2, 3, 4, 5};
vector<int> v2 = {11, 12, 13, 14, 15};
copy(v2.begin(), v2.end(), back_inserter(v1));

其他回答

在一个std::vector中使用for循环连接两个std:: vectors。

    std::vector <int> v1 {1, 2, 3}; //declare vector1
    std::vector <int> v2 {4, 5}; //declare vector2
    std::vector <int> suma; //declare vector suma

    for(int i = 0; i < v1.size(); i++) //for loop 1
    {
         suma.push_back(v1[i]);
    }

    for(int i = 0; i< v2.size(); i++) //for loop 2
    {
         suma.push_back(v2[i]);
    }

    for(int i = 0; i < suma.size(); i++) //for loop 3-output
    {
         std::cout << suma[i];
    }

我更喜欢前面提到的一个:

a.insert(a.end(), b.begin(), b.end());

但是如果你使用c++ 11,有一个更通用的方法:

a.insert(std::end(a), std::begin(b), std::end(b));

另外,这不是问题的一部分,但建议在追加之前使用reserve以获得更好的性能。如果你把向量和它自己连接起来,如果不保留,它就失败了,所以你总是应该保留。


所以基本上你需要:

template <typename T>
void Append(std::vector<T>& a, const std::vector<T>& b)
{
    a.reserve(a.size() + b.size());
    a.insert(a.end(), b.begin(), b.end());
}

对于range v3,你可能会有一个惰性连接:

ranges::view::concat(v1, v2)

演示。

对于提供push_back (string, vector, deque,…)功能的容器:

Std::copy(Std::begin(input), Std::end(input), Std::back_inserter(output))

and

对于提供insert (map, sets)功能的容器:

Std::copy(Std::begin(input), Std::end(input), Std::inserter(output, output.end()))

你可以为+操作符准备自己的模板:

template <typename T> 
inline T operator+(const T & a, const T & b)
{
    T res = a;
    res.insert(res.end(), b.begin(), b.end());
    return res;
}

接下来,使用+:

vector<int> a{1, 2, 3, 4};
vector<int> b{5, 6, 7, 8};
for (auto x: a + b)
    cout << x << " ";
cout << endl;

这个例子给出了输出:

1 2 3 4 5 6 7 8