在ANSI C中定义的结构的STL映射

STL map for an struct defined in ANSI C

本文关键字:结构 映射 STL 定义 ANSI      更新时间:2023-10-16

我在一个混合的C/c++环境中编码。我有一个结构体在C部分,我想收集它在映射容器在c++部分。我认为我应该定义一个自定义的key_compare函数对象,并让STL map::insert() orders节点。然而,我不知道如何修改映射容器自定义map::find()函数。我正在寻找一种方法来自定义map::find()函数做一些更多的key_compare函数等价检查。

请告诉我如何将这些函数放入STL::map或STL::set中?

这是我的结构在C部分(编译与gcc):

typedef struct  iotrace_arh_node 
{
    double time;
    unsigned long long int blkno;
    int bcount;
    u_int flags;
    int devno; 
    unsigned long stack_no;
} iotrace_arh_node_t;

这是我在c++部分(用g++编译)中提出的key_compare和对find()的等价性检查函数:

int key_compare ( struct iotrace_arh_node tempa, struct iotrace_arh_node tempb )
{
return (tempa.blkno-tempb.blkno);
}

int key_equal( struct iotrace_arh_node tempa, struct iotrace_arh_node tempb )
{
    if( (tempa.blkno == tempb.blkno) && (tempa.bcount == tempb.bcount) )
        return 0; // tempa and tempb is equal, node fund in the map
    else if ( (tempb.blkno < tempa.blkno)  )
        return -1;  //tempb is less than tempa
    else if ( (tempb.blkno >= tempa.blkno) && ( tempb.blkno + tempb.bcount < tempa.blkno + tempa.bcount) )      
        return 0; // tempa and tempb is equal, node fund in the map
    else
        return 1;  //tempb is grater than tempa
}

要在映射或集合中使用该类型作为键,需要提供一个"小于"比较,它接受两个参数,如果第一个参数应该在第二个参数之前,则返回true。在set中使用它的最简单方法是将其定义为函数对象:

struct key_compare {
    bool operator()(const iotrace_arh_node & a, const iotrace_arh_node & b) {
        return a.blkno < b.blkno;
    }
};

并将其用作map或set中的"comparator"模板参数:

typedef std::set<iotrace_arh_node, key_compare> node_set;

如果您需要不同的方式来比较键,那么您可以使用不同的比较器创建不同的集合。但是,一旦创建了集合,就不能更改比较器;集合中的对象按照比较器定义的顺序存储,因此更改比较器将使集合不可用。如果您需要通过不同的字段搜索相同的集合,那么请查看Boost。MultiIndex

不需要提供相等比较

标准比较函数在C和c++中是不同的。在C中,正如你所写的,当第一个参数小于、等于或大于第二个参数时,你返回-1、0或1。但是在c++中,你应该重载<操作符,或者编写一个与><操作符并将其名称赋予STL函数。但你应该确保你的><应该是可传递的(即a<b && b<c => a<c)这意味着你的key_compare函数应该是这样的:>

bool key_compare ( const struct iotrace_arh_node& tempa, const struct iotrace_arh_node& tempb )
{
return (tempa.blkno < tempb.blkno);
}

不需要定义key_equal,因为(k1 == k2) <=> (!(k1<k2)&&!(k2<k1))。我敢说,当你插入和查找。

时,你不能使用不同的比较函数。

对于比较器,请参见这里:

struct my_comparer
{
   bool operator() ( const struct iotrace_arh_node& left, const struct iotrace_arh_node& right )
   {
      return left.blkno < rigth.blkno);
   }
}

比较器必须是二元谓词,不能是简单函数。

那么你可以在Map中使用它:

std::map<Key, Data, Compare, Alloc>

(看这里:http://www.cplusplus.com/reference/stl/map/)

Compare和Alloc有默认值

顺便问一下,你的密钥类型是什么?

hth

马里奥