Concatenating two std::vectors

后端 未结 25 2318
予麋鹿
予麋鹿 2020-11-22 12:00

How do I concatenate two std::vectors?

相关标签:
25条回答
  • 2020-11-22 12:08

    If you want to be able to concatenate vectors concisely, you could overload the += operator.

    template <typename T>
    std::vector<T>& operator +=(std::vector<T>& vector1, const std::vector<T>& vector2) {
        vector1.insert(vector1.end(), vector2.begin(), vector2.end());
        return vector1;
    }
    

    Then you can call it like this:

    vector1 += vector2;
    
    0 讨论(0)
  • 2020-11-22 12:09

    Concatenate two std::vector-s with for loop in one std::vector.

        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];
        }
    
    0 讨论(0)
  • 2020-11-22 12:13

    Try, create two vectors and add second vector to first vector, code:

    std::vector<int> v1{1,2,3};
    std::vector<int> v2{4,5};
    
    for(int i = 0; i<v2.size();i++)
    {
         v1.push_back(v2[i]);
    }
    

    v1:1,2,3.

    Description:

    While i int not v2 size, push back element , index i in v1 vector.

    0 讨论(0)
  • 2020-11-22 12:14
    vector1.insert( vector1.end(), vector2.begin(), vector2.end() );
    
    0 讨论(0)
  • 2020-11-22 12:14

    With range v3, you may have a lazy concatenation:

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

    Demo.

    0 讨论(0)
  • 2020-11-22 12:14

    If your goal is simply to iterate over the range of values for read-only purposes, an alternative is to wrap both vectors around a proxy (O(1)) instead of copying them (O(n)), so they are promptly seen as a single, contiguous one.

    std::vector<int> A{ 1, 2, 3, 4, 5};
    std::vector<int> B{ 10, 20, 30 };
    
    VecProxy<int> AB(A, B);  // ----> O(1)!
    
    for (size_t i = 0; i < AB.size(); i++)
        std::cout << AB[i] << " ";  // ----> 1 2 3 4 5 10 20 30
    

    Refer to https://stackoverflow.com/a/55838758/2379625 for more details, including the 'VecProxy' implementation as well as pros & cons.

    0 讨论(0)
提交回复
热议问题