很简单,这段代码有什么问题?
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::tuple
。 std::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/