簡體   English   中英

在std :: map中存儲函數指針

[英]Storing function pointers in a std::map

我試圖將函數指針與結構一起存儲在映射中。 我的想法是在結構中找到特定值時執行相應的功能。 該程序未編譯,當我嘗試通過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指定比較器, _timeset使std::map工作,例如:

struct _timeset
{
    int hr1;
    int min1;
    int secs1;
    bool operator<( const _timeset &t ) const {
        return std::make_tuple( hr1, min1, secs1 ) < std::make_tuple( t.hr1, t.min1, t.secs1 );
    }
};

或者您可以按此處所述將其制作為蘭巴舞

另外,在迭代地圖時,我是否可以執行類似的功能

是的,您可以,也不必復制struct _timeset

int i = 0;
for ( it1 = m1.begin(); it1 != m1.end(); it1++,i++)
{

    const _timeset &_t = it1->first;
     //Check Values in _t, and then execute the corresponding function in the map

        (*it1->second)();
}

如果要存儲具有不同簽名的函數,請使用std::function

typedef std::function<void()> func;
std::map<_timeset, func> m1;

void fun1();
void func2( int );
struct foobar { void func3(); };

m1.insert( std::make_pair( t, func1 ) ); // signature matches, no need for bind
m1.insert( std::make_pair( t, std::bind( func2, 123 ) ) ); // signature does not match func2(123) will be called
foobar *pf = ...;
m1.insert( std::make_pair( t, std::bind( func3, pf ) ) ); // signature does not match, pf->func3() will be called
// etc

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM