简体   繁体   English

将std :: unordered_map值移动到std :: vector

[英]Moving an std::unordered_map values to std::vector

Is there any way to move unordered_map values to a vector? 有没有办法 unordered_map移动到向量? All the ways I was able to find copy values (like in my example) instead of using something similar to std::move . 我能够找到复制值的所有方法(比如我的例子),而不是使用类似于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 . 我想不复制值,所以我可以保留shared_ptr foo的唯一性,我稍后会更改为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. 提前感谢您提供所有有用的答案。

You can certainly move shared_ptr from unordered_map to vector . 你当然可以将shared_ptrunordered_map移动到vector All you need to do is to use std::move in your example: 您需要做的就是在您的示例中使用std::move

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. 请记住,在此操作之后,您可能希望清除地图,因为它现在包含空对象。

@SergeyA's answer already covers the essential part here, let me nevertheless add a solution based on range-v3 , it shows where one part of the language is heading to with C++20. @ SergeyA的答案已经涵盖了这里的基本部分,但是我还是添加了一个基于range-v3的解决方案,它显示了C ++ 20中语言的一部分。

#include <range/v3/view/map.hpp>
#include <range/v3/view/move.hpp>

using namespace ranges;

/* Setup mapOfObjects... */

const std::vector<Class> someVector = mapOfObjects | view::values | view::move;

The STL in its current shape isn't that bad either, but admittetly more verbose: 目前形状的STL也不是那么糟糕,但是更加冗长:

#include <algorithm>
#include <iterator>

std::vector<Class> someVector;

std::transform(std::move_iterator(mapOfObjects.begin()),
        std::move_iterator(mapOfObjects.end()),
        std::back_inserter(someVector),
        [](std::pair<int, Class>&& entry){ return std::move(entry.second); });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM