是否可以覆盖 "find" 和 "erase" boost::bimaps::bimap.left 的方法?怎么办?

Is it possible to override "find" and "erase" methods of boost::bimaps::bimap.left? How to do it?

本文关键字:bimap bimaps left 方法 怎么办 boost 覆盖 find erase 是否      更新时间:2023-10-16

我有以下内容:

struct foo_and_number_helper {
std::string foo;
uint64_t number;
};
struct foo_and_number {};
struct bar {};
using my_bimap = boost::bimaps::bimap<
boost::bimaps::unordered_set_of<boost::bimaps::tagged<foo_and_number_helper, foo_and_number>>, 
boost::bimaps::multiset_of<boost::bimaps::tagged<std::string, bar>>
>;
my_bimap instance;

我希望能够调用这样的查找和擦除方法:
instance.left.find("foo")而不是instance.left.find({"foo",1})instance.left.erase("foo")
而不是instance.left.erase({"foo",1})

我只想使用"foo_and_number_helper"的"foo"部分,而不是从左侧调用的方法查找和擦除的两个部分。如何实现?我试图阅读 bimap 实现,但我仍然很难做到。

我已经问了更广泛的问题:视图一侧与视图值的另一侧具有不同键的情况下C++bimap是否可能?怎么做? 从评论中我必须覆盖operator <,但我什至不确定这一点以及是否足够。

我会在这里boost::multi_index_containerboost::bimap

namespace bmi = boost::multi_index;
struct ElementType { 
std::string foo; 
std::string bar;
uint64_t number; 
}
using my_bimap = boost::multi_index_container<
ElementType,
bmi::indexed_by<
bmi::unordered_unique<
bmi::tagged<struct Foo>, 
bmi::member<ElementType, std::string, &ElementType::foo>
>,
bmi::ordered<
bmi::tagged<struct Bar>, 
bmi::member<ElementType, std::string, &ElementType::bar>
>,
// and others like
bmi::sequenced<
bmi::tagged<struct InsertionOrder>
>
>
>;

然后你会像

my_bimap instance;
instance.get<Foo>().find("foo");
instance.get<Bar>().erase("bar");
std::cout << instance.get<InsertionOrder>()[10].foo;

即,您没有leftright视图,而是拥有任意数量的视图

所以我按照@Caleth的回答对其进行了调整:

#include <boost/multi_index/hashed_index.hpp>
#include <boost/bimap/bimap.hpp>
using namespace std;
struct ElementType { 
string foo; 
string bar;
uint64_t number; 
};
using namespace boost::multi_index;
using my_bimap = multi_index_container<
ElementType,
indexed_by<
hashed_unique<member<ElementType, string, &ElementType::foo>>,
ordered_non_unique<member<ElementType, string, &ElementType::bar>>
>
>;
int main() {
my_bimap instance;
instance.insert({"foo", "bar", 0});
instance.insert({"bar", "bar", 1});
cout << instance.get<0>().find("bar")->foo << endl;
cout << instance.get<0>().find("bar")->bar << endl;
cout << instance.get<0>().find("bar")->number << endl;
auto range = instance.get<1>().equal_range("bar");
for (auto it = range.first; it != range.second; ++it) {
cout << it->foo << endl;
cout << it->number << endl;
}
cin.sync();
cin.ignore();
}

输出:

bar
bar
1
foo
0
bar
1

所以是的,它没有回答我的问题,但我认为我实现了我想要的。