'How to move elements from a set to a vector efficiently?

I have a std::set<vector<int>> from which I would like to move (not copy) elements to a std::vector<vector<int>>. How do I do this?

I tried using move (which I use to move between vectors) with the following piece of code but it won't compile.

#include<iostream>
#include<set>
#include<vector>
using namespace std;

int main(){
    set<vector<int>> res;
    vector<int> first = {1,2,3};
    vector<int> second = {4,5,6};
    res.insert(first);
    res.insert(second);
    vector<vector<int>> ans;
    for(auto i : res){
        ans.emplace_back(ans.end(),move(i));
    }
    return 0;
}


Solution 1:[1]

A set<T> does not contain Ts; it contains const Ts. As such, you cannot simply move objects out of it.

Solution 2:[2]

This is one of reasons why we still may need const_cast sometimes:

for(auto& i : res){
    ans.emplace_back(ans.end(),move(const_cast<T&>(i)));
}

No point to do it for int elements though.

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 Nicol Bolas
Solution 2 Sergei Krivonos