'How do I avoid creating a temporary vector in C++?

In the following minimal example, v1 and v2 and slices of vector v and these slices are elements of other vector vv.

#include<vector>

int main(){
 std::vector<int> v{0,1,2,3,4,5};
 std::vector<int> v1(v.begin(), v.begin() + 2);
 std::vector<int> v2(v.begin() + 2, v.end());

 std::vector<std::vector<int>> vv(2);
 vv[0] = v1;
 vv[1] = v2;

}

Is it possible to directly assign slices of v to vv without creating v1 and v2 explicitly?

c++


Solution 1:[1]

You can use vector::assign(), eg:

#include <vector>

int main(){
    std::vector<int> v{0,1,2,3,4,5};

    std::vector<std::vector<int>> vv(2);
    vv[0].assign(v.begin(), v.begin() + 2);
    vv[1].assign(v.begin() + 2, v.end());
}

Solution 2:[2]

You can also pass them to the constructor.

#include <iostream>
#include<vector>

int main() {
    std::vector<int> v{ 0,1,2,3,4,5 };

    std::vector<std::vector<int>> v3 {
            { v.begin(), v.begin() + 2},
            { v.begin() + 2, v.end() }
    };

}

Solution 3:[3]

You could emplace them

#include<vector>

int main(){
 std::vector<int> v{0,1,2,3,4,5};

 std::vector<std::vector<int>> vv;
 // vv.reserve(2);
 vv.emplace_back(v.begin(), v.begin() + 2);
 vv.emplace_back(v.begin() + 2, v.end());
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Remy Lebeau
Solution 2 Jimmy Loyola
Solution 3 Thomas Sablik