c++ - 搜索当前类实例的 boost::bimap

标签 c++ boost bimap

好的,所以我声明了一个 boost::bimap:

boost::bimap<object*, position> object_list;

其中 object 和 position 分别是一个类和一个结构。

在 bimap 中存储的当前对象中,我想找到它自己的条目。

我目前正在尝试这样做:

void order::do_thing() {
    ...
    position pos = object_list.left.at(this);
    ...
}

我在解析错误输出时遇到问题,但似乎 bimap 的 at 函数不喜欢它的常量特性和/或引用特性(是的,我知道这是一个右值)。

执行此搜索的正确/建议方法是什么?

这是错误的片段:

order.cpp:117:56:   required from here
/usr/include/boost/bimap/container_adaptor/associative_container_adaptor.hpp:207:56: error: no match for call to ‘(const boost::bimaps::container_adaptor::detail::key_to_base_identity<object*, object* const>) (order* const&)’
                 this->template functor<key_to_base>()(k)

(添加编辑以解决 sehe 的评论并指出问题)

如果我的帖子不礼貌,我深表歉意,我都是在 SO 上发帖的新手,而且我假设只是转储我的所有代码(仅包括这部分代码的自定义对象和模板是数百个行)会被认为是错误的形式,所以我将其削减到(我认为的)最低限度以仍然能解决问题。

为了解决测试用例链接,我确实编写了测试用例。在这种情况下,我将 vector 换成 bimap 以添加到位置代码中,这实际上无法编译(尽管我会说我不是很明确地指出它是编译错误,而不是堆栈跟踪)。我假设您 (sehe) 认为我在谈论运行时错误,否则我看不出链接是如何相关的。

无论如何,我正在将代码削减到实际的最小值以重现错误,以便我可以将其发布在这里,然后才意识到实际问题。如上所示,bimap 包含值 < 对象* , position>但是试图将自己插入 bimap 的类是一个 order 类:void 订单 ::do_thing() {

原来是简单的类型错误。对不起,大家,问了一个非常愚蠢的问题。我想这就是我凌晨 3 点处理项目的收获。

最佳答案

没有问题。

我能想到的唯一陷阱是你有 this 隐式常量。在这种情况下, map 将不得不采用指向 const object 的指针!

请在此处查看此示例。取消注释 //const 以查看 const 的变化:

Live On Coliru (非常量)

Live On Coliru (常量)

#include <boost/bimap.hpp>
#include <iostream>

using position = std::string;

#define USE_CONST // const

struct object {
    template <typename BiMap>
    position get_position(BiMap const& bimap) USE_CONST {
        return bimap.left.at(this);
    }
};

int main() {
    std::vector<object> instances(10);

    boost::bimap<object USE_CONST*, position> mapping;

    for (auto& instance : instances)
        mapping.insert({&instance, "instance #" + std::to_string(mapping.size()+1)});

    for (auto& instance : instances)
        std::cout << "Instance reports " << instance.get_position(mapping) << "\n";
}

打印

Instance reports instance #1
Instance reports instance #2
Instance reports instance #3
Instance reports instance #4
Instance reports instance #5
Instance reports instance #6
Instance reports instance #7
Instance reports instance #8
Instance reports instance #9
Instance reports instance #10

关于c++ - 搜索当前类实例的 boost::bimap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33195239/

相关文章:

c++ - 完美的转发可变参数模板,为所选类型按值传递

c++ - 给定一组点,使用 voroni 近似将空间分割成多边形区域

c++ - Debian 测试中缺少 `/usr/lib/libboost_unit_test_framework-mt.so'

c++ - 用于枚举的 boost::bimap

c++ - 比较 2 个 c++ std::lists 的最快方法,在每次迭代中改变

c++ - 多个 Nt 函数在 Windows 7 x32 上返回 STATUS_WAIT_0

c++ - 局部变量如何隐藏全局变量

c++ - 使用 Boost Dijkstra 和指定的 MAX DISTANCE 查找最短路径

c++ - 任何可用的实现,如 Loki 的 AssocVector,但具有 Boost 的 Bimap 的功能?

c++ - c++11 中是否有 Boost.Bimap 替代方案?