gpt4 book ai didi

c++ - 如何更新 boost multi_index_container 的值?

转载 作者:行者123 更新时间:2023-11-28 01:42:08 25 4
gpt4 key购买 nike

我使用 multi_index_container 来跟踪插入顺序并进行映射工作(如 Java 的 LinkedMap)。

#include <boost/multi_index_container.hpp>
#include <boost/multi_index/member.hpp>
#include <boost/multi_index/ordered_index.hpp>
#include <boost/multi_index/random_access_index.hpp>

#include "CppUnitTest.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;

template<typename KeyType, typename MappedType>
struct LinkedMap {
typedef std::pair<KeyType, MappedType> value_type;
typedef boost::multi_index_container<
value_type,
boost::multi_index::indexed_by<
boost::multi_index::random_access<>,
boost::multi_index::ordered_unique<
boost::multi_index::member<value_type, KeyType, &value_type::first>
>
>
> type;
};

TEST_CLASS(LinkedMapTest) {
public:
TEST_METHOD(ShouldUpdateEntry) {
LinkedMap<int, std::wstring>::type userMap;
userMap.push_back(std::make_pair(1, L"John"));
userMap.push_back(std::make_pair(1, L"Tom")); // 2nd push_back
auto& idToNameMap = userMap.get<1>();
auto& iter = idToNameMap.find(1);
Assert::AreEqual(std::wstring(L"Tom"), iter->second);
}
};

测试用例失败。

Result Message: Assert failed. Expected:< Tom> Actual:< John>

这意味着第二次 push_back 不会更新值。

我的代码有什么问题?我如何实现 LinkedMap?

最佳答案

您指定的有序索引唯一:

boost::multi_index::ordered_unique<
boost::multi_index::member<value_type, KeyType, &value_type::first>
>

使其非唯一以允许重复键:

boost::multi_index::ordered_non_unique<
boost::multi_index::member<value_type, KeyType, &value_type::first>
>

或者,如果您的 key 需要是唯一的并且您想要更新现有条目,您可以执行以下操作(未经测试):

auto& idToNameMap = userMap.get<1>();
auto& iter = idToNameMap.find(1);
if(iter != idToNameMap.end()) {
idToNameMap.modify(iter, [](auto& p){p->second = "Tom";});
}

以下是另一种您可能会觉得更合胃口的方法(同样,未经测试):

LinkedMap::iterator push_back_or_update(LinkedMap& m,const LinkedMap::value_type& x) {
auto r=m.push_back(x);
if(!r.second) m.replace(r.first, x);
return r.first;
}

关于c++ - 如何更新 boost multi_index_container 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46727011/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com