C++:使用 std::function 在多重集中插入​​元组,并保持顺序

标签 c++ vector insert std-function multiset

很简单,这段代码有什么问题?

    typedef std::function<double()>                             Event;
    typedef std::tuple <double, std::function<double()>>        Event_handle;

    std::multiset < Event_handle > event_multiset;
    std::vector < Event_handle > event_vector;
    void add_event_handler(double time, Event func_object)
    {
        // multiset version gives an error 
        // event_multiset.insert (std::make_tuple(time, func_object));
        // vector is ok
        event_vector.push_back(std::make_tuple(time, func_object));
    }

使用 g++ 4.7.2 编译- 只需使用命令 g++ -std=c++11 main.cpp

为什么我要这样做?

该程序实时运行,add_even_handler函数包含 double 类型的值叫time (注意,这里的time变量与时钟或实际时间无关,它只是一个double类型的递增对象)。因此,当用户添加某个事件时,它将在某个时间被调用。

标准下的多集容器会按某种顺序整理对象(通常,如果不是总是, std::less<T> )。然后循环容器,我可以调用 Event随着变量变化的增加double time .

问题是什么?

正如 KyleC 所指出的(参见他的回答),std::function<>编译器不理解在​​什么过程中进行排序

我是如何克服这个问题的

你每天都会学到新东西。上面的代码是通过最初混合 std::multiset 过度思考问题的结果和std::tuplestd::map<T,S>std::multimap<T,S>也按关联的 key 排序在本例中,其类型为 double ,默认情况下,标准又是 std::less<T> 。因此,我没有执行上述操作,而是执行了类似于以下操作的操作

std::multimap <double, event> event_map;
void add_event_handler(double time, Event func_object)
{
    // multimap is ok
    event_map.insert(std::make_pair(time,func_object));
}

这只是写在这里,希望它可以帮助人们,尽管很明显,但仍然如此。

最佳答案

问题在于多重集是有序的。

您收到的错误是:

Error   1   error C2678: binary '<' : no operator found which takes a left-hand operand of type 'const std::function<_Fty>' (or there is no acceptable conversion)  
error C2088: '<' : illegal for class    C:\Program Files (x86)\Microsoft Visual Studio 11.0\VC\include\tuple    52

多重集不知道如何处理这个问题,因为它不知道如何对多重集进行排序。

Internally, multiset containers keep all their elements sorted following the criterion specified by its comparison object. The elements are always inserted in its respective position following this ordering.

使用 vector 有什么问题?

-- 根据您的评论,我认为 map 非常适合您的目的。

std::map < float, Event > event_map;
event_map.insert(std::make_pair(time, func_object));

关于C++:使用 std::function 在多重集中插入​​元组,并保持顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15772761/

相关文章:

c++ - 在 Eclipse 中运行多个 Qt 测试

c++ - 获取错误

python - SWIG 文件更改后如何重建项目?

c++ - 将 std::vector 转换为数组

c++ - 从哑指针 vector 切换到 boost::shared_ptr 时出现问题

c++ - Visual C++ Express 2008 错误与 MSVCP90D.dll

database - 如何在数据库 : BLOB or ARRAY? 中存储向量

c++ - 插入的最有效数据结构,然后按不同条件排序

c# - 字符串插入数据库时​​单引号转义

php - 在 sp 中多次插入