0

我在混合 C/C++ 环境中编码。我在 C 部分有一个结构,我想将它收集在 C++ 部分的地图容器中。我想我应该定义一个自定义的key_compare函数对象,并让 STL map::insert()对节点进行排序。但是我不知道如何修改地图容器以自定义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++ 编译)中为find()提出的key_compare和等价检查函数:

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
}
4

3 回答 3

2

标准比较函数在 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)). 并且 AFAIK 在插入和查找时不能使用不同的比较功能。

于 2011-04-20T04:43:52.290 回答
2

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

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

并将其用作地图或集合中的“比较器”模板参数:

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

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

您不需要提供相等比较。

于 2011-04-20T04:50:27.157 回答
1

对于比较器,请参见此处:STL Map with custom compare function object

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

}

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

然后你可以在地图中使用它:

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

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

Compare 和 Alloc 具有默认值。

顺便说一句,您的密钥类型是什么?

hth

马里奥

于 2011-04-20T04:46:35.200 回答