【发布时间】:2015-12-12 02:03:24
【问题描述】:
我正在尝试将函数指针与结构一起存储在映射中。这个想法是当我在结构中找到特定值时执行相应的功能。程序没有编译,当我试图通过 std::make_pair 将数据插入地图时给我很多错误。这是我编写的代码。请指导我在这里做错了什么..
#include "stdafx.h"
#include <iostream>
#include <string>
#include <map>
struct _timeset
{
int hr1;
int min1;
int secs1;
};
_timeset t1 = { 17, 10, 30 };
void fun1(void)
{
std::cout << "inside fun1\n";
}
void fun2(void)
{
std::cout << "inside fun2\n";
}
void fun3(void)
{
std::cout << "inside fun3\n";
}
std::map<_timeset, void(*)()> m1;
int main()
{
m1.insert(std::make_pair(t1, fun1)); //Compiling errors here
return 0;
}
我的 STL 基础很差。我正在使用 VS2013 编译器。 另外,在迭代地图时,我可以使用以下内容执行相关功能吗:
std::map<_timeset, void(*)()>::iterator it1;
int i = 0;
for (i=0,it1 = m1.begin(); it1 != m1.end(); it1++,i++)
{
_timeset _t = it1->first;
//Check Values in _t, and then execute the corresponding function in the map
(*it1->second)();
}
非常感谢,
【问题讨论】:
-
如果您有编译器错误,您应该将它们包含在问题中。
-
映射键(在您的情况下为
_timeset)应该为它们定义operator<。 -
没有足够的空间容纳所有错误
-
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\xstddef(193): error C2784: 'bool std::operator &,const std::tuple<_types1...> &)' : 无法从 'const _timeset'推导出 'const std::tuple<_types...> &' 的模板参数>
-
顺便说一句,
typedef关键字对函数指针非常有用。typedef比函数指针语法更易读(而且打字更少)。