c++ - 使用 Boost.bimap 时如何避免键复制?

标签 c++ boost

我是 using Boost.bimap for implementing a LRU cache,有一些包含字符串的复杂键

问题是我每次调用 find() 时都会复制 key 。我想避免这种不必要的复制(一般来说:制作尽可能少的字符串拷贝,也许通过模板?)

一个最小的测试用例(带有 gist version ):

#include <string>
#include <iostream>

#include <boost/bimap.hpp>
#include <boost/bimap/list_of.hpp>
#include <boost/bimap/set_of.hpp>

class Test
{
public:
    struct ComplexKey
    {
        std::string text;
        int dummy;

        ComplexKey(const std::string &text, int dummy) : text(text), dummy(dummy) {}

        ~ComplexKey()
        {
            std::cout << "~ComplexKey " << (void*)this << " " << text << std::endl;
        }

        bool operator<(const ComplexKey &rhs) const
        {
            return tie(text, dummy) < tie(rhs.text, rhs.dummy);
        }
    };

    typedef boost::bimaps::bimap<
    boost::bimaps::set_of<ComplexKey>,
    boost::bimaps::list_of<std::string>
    > container_type;

    container_type cache;

    void run()
    {
        getValue("foo", 123); // 3 COPIES OF text
        getValue("bar", 456); // 3 COPIES OF text
        getValue("foo", 123); // 2 COPIES OF text
    }

    std::string getValue(const std::string &text, int dummy)
    {
        const ComplexKey key(text, dummy); // COPY #1 OF text
        auto it = cache.left.find(key); // COPY #2 OF text (BECAUSE key IS COPIED)

        if (it != cache.left.end())
        {
            return it->second;
        }
        else
        {
            auto value = std::to_string(text.size()) + "." + std::to_string(dummy); // WHATEVER...
            cache.insert(typename container_type::value_type(key, value)); // COPY #3 OF text

            return value;
        }
    }
};

最佳答案

Bimap 没有直接使用 std:map(我这么说是因为您正在使用 set_of),而是通过不同的容器适配器创建 View ,并在此过程中 key 被复制。不可能按照您在问题中定义 bimap 的方式显着 boost 性能。

为了在 ComplexKey 方面从 bimap 获得更好的性能,您宁愿必须存储指向 ComplexKey 的指针(最好是原始的;没有隐含的 key 所有权bimap)并提供你自己的分类器。指针的复制成本很低,缺点是您必须与映射并行管理键的生命周期。

做一些事情,

std::vector<unique_ptr<ComplexKey>> ComplexKeyOwningContainer;
typedef boost::bimaps::bimap<
    boost::bimaps::set_of<ComplexKey*, ComplexKeyPtrSorter>,
    boost::bimaps::list_of<std::string>
    > container_type;

请注意,如果您追求性能,您还需要注意 std::string,它是您的 bimap 的另一侧。它们可能非常昂贵,临时的很常见,并且它们会遇到与 ComplexKey key 相同的问题。

关于c++ - 使用 Boost.bimap 时如何避免键复制?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21112208/

相关文章:

c++ - if/switch 中的声明

c++ - 有没有办法从函数内部更改外部对象

c++ - 使用extern “C”从C++调用C代码

c++ - 遍历 boost::multi_array 的维度

c++ - 使用 boost-spirit 的函数解析器

c++ - 侵入式智能指针的引用计数器

c++ - C++ 中的扩展内联汇编 : Is it necessary to preserve volatile registers?

c++ - 如何使用 boost 实现这种特定的日期时间格式?

c++ - 如何使用 lambda 创建 ReadHandler

c++ - 在 C++ 中的两个不同核心中创建两个线程