c++ STD::find_if使用结构谓词
C++ STD::find_if using structure predicate
key_struct kStruct;
kStruct.x = 2;
std::find_if(m_cueCommands.begin(), m_cueCommands.end(), find_MyInt(kStruct));
struct key_struct
{
int x;
string y;
string z;
}
struct find_myInt : std::unary_function<key_struct, bool>
{
int x;
find_myInt(key_struct kStruct):myInt(kStruct.x){}
bool operator()(key_struct const& m) const
{
return m.x == myInt;
}
};
我很确定我有这一点搞砸了,但我认为它是适度接近。我要做的是,我有key_struct作为我地图中的键。我希望能够搜索密钥并返回我设置key_struct的信息。如果我将key_struct设置为x = 2,那么我只想返回int x等于2的地方。如果我设置x = 2和y = "testString",那么我只想返回x = 2和y = "testString"的值的子集。
我相信我的方法很接近,但是,我想我遗漏了一些东西。想法吗?
你总是想和x比较吗?还是只当x != 0?
Btw,在你的结构构造函数中似乎有一个错误:没有名为myInt
的成员,因此它应该是:find_myInt(key_struct kStruct) : x(kStruct.x){}
。但这并不重要,无论如何它都需要被改变。
这是我要尝试的。这是未经测试的,可能包含错误,布尔返回值的"计算"效率极低。无论如何…
要使用它,创建一个你想要匹配的结构体,正如你可以从代码中看到的,它只会尝试匹配x > 0, y != "" and z != ""
。因此,如果将"search"结构体设置为x = 5, y = "" and z = ""
,它将匹配x == 5
(y &Z可以是任意的)
typedef std::pair<key_struct, your_value_type> yourMapType;
struct find_myStruct : std::unary_function<key_struct, bool>
{
private:
key_struct myStruct;
public:
find_myInt(key_struct const & kStruct): myStruct(kStruct) {}
bool operator() (yourMapType const & m) const
{
bool result = true;
if (myStruct.x > 0)
result &= (myStruct.x == m.first.x);
if (myStruct.y != "")
result &= (myStruct.y == m.first.y);
if (myStruct.z != "")
result &= (myStruct.z == m.first.z);
return result;
}
};
[Edit]注意到您想要使用映射,所以我相应地更新了代码。仍然非常未经测试,请随意指出错误。
[Edit 2]如果您在实际创建映射时遇到问题,因为您在key_struct上没有严格的弱排序,那么应该这样做。
同样,未经测试的可能包含错误。所有if
的效率也很低,但是…请随意使用您最喜欢的卡诺地图求解器(我想到了BMin)。
struct cmp_key_struct
{
bool operator() (key_struct const & lhs, key_struct const & rhs) const
{
bool result = (lhs.x < rhs.x);
if ((!result) && (lhs.x == rhs.x))
{
result = (lhs.y < rhs.y);
if ((!result) && (lhs.y == rhs.y))
result = (lhs.z < rhs.z);
}
return result;
}
};
std::map<key_struct, your_value_type, cmp_key_struct> yourMap;
更正后的版本:
struct find_myInt : std::unary_function<key_struct, bool>
{
int myInt; /// HERE
find_myInt(key_struct kStruct):myInt(kStruct.x){}
bool operator()(key_struct const& m) const
{
return m.x == myInt;
}
};
您不需要在地图上使用find_if
。如果您试图使用结构作为映射键,如您所说,您需要提供"严格弱排序"的比较。例如,使用"<"而不是"=="。然后将其与地图进行比较。或者重载struct中的<
操作符。您可以使用[]
运算符或map
的find()
方法进行O(log n)搜索,其中find_if
为O(n)。
- 如何循环打印顶点结构
- 通过方法访问结构
- 使用不带参数的函数访问结构元素
- std::condition_variable::wait()如何评估给定的谓词
- 预处理器:插入结构名称中的前一个行号
- 为什么在没有显式默认构造函数的情况下,将另一个结构封装在联合中作为成员的结构不能编译
- 孤立代码块在结构中引发异常
- 有什么方法可以遍历结构吗
- 如何在 C# 中映射双 C 结构指针?
- 如何在C++中使用结构生成映射
- 无法将结构注册为增强几何体3D点
- 多成员Constexpr结构初始化
- C++将文本文件中的数据读取到结构数组中
- 如何重构类层次结构以避免菱形问题
- 如何在C++中序列化结构数据
- std::vector的包装器,使数组的结构看起来像结构的数组
- 没有为自己的结构调用列表推回方法
- 是否可以使用给定参数为结构创建推力的功能谓词?
- STL中使用的C++自定义比较类型(函数谓词与较少结构)
- c++ STD::find_if使用结构谓词