Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Moving an std::unordered_map values to std::vector

Tags:

c++

c++11

c++17

Is there any way to move unordered_map values to a vector? All the ways I was able to find copy values (like in my example) instead of using something similar to std::move.

I would like to not copy values so I can retain uniqueness of shared_ptr foo, which I'll later change to unique_ptr.

class Class {
    public:
        std::shared_ptr <int> foo = std::shared_ptr <int> (new int (5));
};

int main() {
    std::unordered_map <int, Class> mapOfObjects({
                                                  {1, Class()},
                                                  {2, Class()},
                                                  {3, Class()},
                                                  {4, Class()},
                                                  {5, Class()} }); 
    std::vector <Class> someVector;

    for (auto &object : mapOfObjects) {

        someVector.push_back(object.second);
        std::cout << "Is unique?  " << ( someVector.back().foo.unique() ? "Yes." : "No.")                    
            << std::endl << std::endl;
    }  
}

Thank you in advance for all helpful answers.

like image 702
McKlobasa Avatar asked Sep 09 '26 03:09

McKlobasa


1 Answers

You can certainly move shared_ptr from unordered_map to vector. All you need to do is to use std::move in your example:

someVector.push_back(std::move(object.second));

Keep in mind, after this operation, you might want to clear the map, as it now contains empty objects.

like image 168
SergeyA Avatar answered Sep 10 '26 17:09

SergeyA



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!