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

Viewed 154

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?

3 Answers

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

}

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

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());
}
Related