我第一次在C++代码中使用std :: find_if函数。我想要执行的示例和逻辑非常简单,但不知何故我无法使其工作。C++,find_if不工作
我所创建的“取景器”类是这样的:
/**
* @class message_by_id_finder
* @brief A class to find the matching lane wrapper
*/
class message_by_id_finder
{
public:
/** @brief constructor */
explicit message_by_id_finder(int id) :
m_myMessage(id) {
}
/** @brief the comparing function */
bool operator()(const AppMessage& message) const {
return message.messageId == m_myMessage;
}
private:
/// @brief The id of the searched object
int m_myMessage;
};
然后,我用它的方式如下:
// Loop messages
for (vector<AppMessage>::iterator it = messages.begin(); it != messages.end() ; ++it) {
// Match message with the registered by the App
AppMessage m = *it;
vector<AppMessage>::iterator it2 = find_if(m_messages.begin(), m_messages.end(), message_by_id_finder(m));
if (it2 != m_messages.end()) {
// FOUND!
} else {
// NOT FOUND
}
}
我循环的m_messages矢量和有匹配的ID成员但是它始终是0x00。我在做什么特别错误?
非常感谢您提前。
PD:以防万一,另一片了解问题有用代码:
/**
* @struct AppMessage
* @brief Information of a message carrying a result of the App.
*/
struct AppMessage {
int messageId;
float payloadValue;
};
您的`operator()`实现是反模式。代码应该写成`return id = m_myMessage;`代替。 **从不**写`如果(条件)返回true;否则返回false;`。 – 2010-11-25 15:22:30
operator()`缺少一个大括号。 `it2!= m_messages.end()`表示发现了消息id *,而不是它。我建议你写一个完整的程序,编译和展示你感到惊讶的行为,然后提出关于该程序的问题。否则,你可能只是整天得到有关拼写错误的答案,其中没有一个出现在你的真实代码中。 – 2010-11-25 15:27:37
谢谢康拉德。但是,不使用你提到的模式会导致错误?除此之外是'return id = m_myMessage;'正确?不应该是'返回ID == m_myMessage;'? – Julen 2010-11-25 15:27:59