我第一次在 C++ 代码中使用 std::find_if 函数。我想要执行的示例和逻辑非常简单,但不知何故我无法使其工作。
我以这种方式创建了“finder”类:
/**
* @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 vector ,其中有与 id 匹配的成员,但 it2 始终为 0x00。我做错了什么吗?
非常感谢您。
PD:以防万一,其他有助于理解问题的代码:
/**
* @struct AppMessage
* @brief Information of a message carrying a result of the App.
*/
struct AppMessage {
int messageId;
float payloadValue;
};
最佳答案
你要明白什么find_if
在内部执行以便正确使用它。 cplusplus reference该网站提供了一些基本代码片段,可能有助于理解算法的实际作用(但请记住,这只是用于教育目的的“伪代码”,而非实际实现)。这是本网站对 std::find_if
的描述。 :
template<class InputIterator, class Predicate>
InputIterator find_if ( InputIterator first, InputIterator last, Predicate pred )
{
for ( ; first!=last ; first++ ) if ( pred(*first) ) break;
return first;
}
您可以看到,为序列中的每个元素调用谓词。在这里,你有一个 std::vector<AppMessage>
所以提供的谓词应该可以用 AppMessage
调用.
将谓词更改为此应该可以解决问题:
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 &appMessage) const {
return appMessage.messageId == m_myMessage;
}
private:
/// @brief The id of the searched object
const int m_myMessage;
}
另请注意,我做了 operator()
和 m_myMessage
const(为什么?因为我可以!)。
关于C++,find_if 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4278468/