C++ 如何从STL容器中获取仅移动类型? 让我们考虑 STD::无序代码集 STD::UnQuyYPPTR 。我可以把集合中的一个元素移到别处吗 #include <unordered_set> #include <iostream> #include <memory> #include <vector> int main() { std::unordered_set<std::unique_ptr<int>> mySet; mySet.insert(std::make_unique<int>(1)); mySet.insert(std::make_unique<int>(2)); mySet.insert(std::make_unique<int>(3)); std::vector<std::unique_ptr<int>> myVector; for (auto&& element : mySet) { std::cout << *element << std::endl; //myVector.push_back(element); won't compile as you can only get a const ref to the key } } #包括 #包括 #包括 #包括 int main() { std::无序的_集mySet; mySet.insert(std::make_unique(1)); mySet.insert(std::make_unique(2)); mySet.insert(std::make_unique(3)); std::vector myVector; 用于(自动和元素:mySet) { std::cout

C++ 如何从STL容器中获取仅移动类型? 让我们考虑 STD::无序代码集 STD::UnQuyYPPTR 。我可以把集合中的一个元素移到别处吗 #include <unordered_set> #include <iostream> #include <memory> #include <vector> int main() { std::unordered_set<std::unique_ptr<int>> mySet; mySet.insert(std::make_unique<int>(1)); mySet.insert(std::make_unique<int>(2)); mySet.insert(std::make_unique<int>(3)); std::vector<std::unique_ptr<int>> myVector; for (auto&& element : mySet) { std::cout << *element << std::endl; //myVector.push_back(element); won't compile as you can only get a const ref to the key } } #包括 #包括 #包括 #包括 int main() { std::无序的_集mySet; mySet.insert(std::make_unique(1)); mySet.insert(std::make_unique(2)); mySet.insert(std::make_unique(3)); std::vector myVector; 用于(自动和元素:mySet) { std::cout,c++,c++11,memory,containers,move,C++,C++11,Memory,Containers,Move,在C++03、C++11和C++14中,而不是直接使用。您必须将类型更改为类似于: template <class T> struct handle { mutable std::unique_ptr<T> owning_ptr; T* observing_ptr; // enforce that observing_ptr == owning_ptr.get() on construction // define operator<, h

在C++03、C++11和C++14中,而不是直接使用。您必须将类型更改为类似于:

template <class T>
struct handle {
    mutable std::unique_ptr<T> owning_ptr;
    T* observing_ptr; // enforce that observing_ptr == owning_ptr.get() on construction

    // define operator<, hash, etc. in terms of the observing ptr
};

您可以使容器包含一个可变标记的并集,如智能指针和同意排序的哑指针,以及一个在返回智能时从智能切换到哑指针的操作。提取智能,删除哑指针,bob是您的叔叔。@Yakk比您先一步:)除了使它不是并集,但是的,它可以是。Should不是
handle
而不是
handle
?@Yakk和@Barry谢谢,我想我会选择这个方便的
handle
作为一个联合!;)一对或一个结构类似于联合;)你也可以使用一个独特的ptr,带有一个特殊的deleter,将移动到默认删除理解为“转换到哑指针”。请注意,如果
mySet
是一个
std::vector
,则不会出现此问题;这是一个特殊的问题。还请注意,如果您成功移动它,它可能会对该集执行其他未定义的操作,因为“从中移动”对象不再有效,例如,对于插入或查找,因此必须小心n完全不使用容器。@metal我可能做错了什么,但我只在向量上有相同的编译错误,请参阅:.edit:My bad,与
std::move
一起工作。谢谢!新代码:介绍了一种有用的技术,虽然很难看,但很有效。该代码用于擦除,但可以修改为move/extract inst公元
std::unordered_set<handle<int>> mySet;
// initialize as appropriate

for (auto& elem : mySet) {
    myVector.push_back(std::move(elem.owning_ptr));        
}
mySet.clear();
for (auto it = mySet.begin(); it != mySet.end();  
{
    std::cout << **it << std::endl;
    myVector.push_back(std::move(
        mySet.extract(it++).value()));
}