在ANSI C中定义的结构的STL映射
STL map for an struct defined in ANSI C
我在一个混合的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
马里奥- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- C++匿名结构作为std::映射值
- 添加静态constexpr成员是否会更改结构/类的内存映射
- C++:映射结构中的结构指针
- 无法添加多个键以映射将结构作为键
- 如何在 c++ 中创建结构向量的映射
- c++ 嵌套结构映射找不到成员
- 带有结构映射的 C++ 向量?
- Unity C#和C 结构映射
- 使用 std::vector 将C++结构映射到 C#
- C++stl::使用结构映射find
- 如何在C++中把结构映射到字符正确的方法
- 更好的数据结构映射函数与多个参数(键)
- 将PolarSSL x509_cert结构映射到pkcs# 11 X.509对象
- 为什么我的JNA结构映射产生奇怪的字段值
- 在函数中填充结构映射的最好方法是什么?
- 如何解决声明结构映射时的编译错误
- 数据结构-C++映射:需要智能算法
- 使用字符串键初始化结构映射