In my code below I want to inform for_each if I find the item? How do that?
#include <list>
#include <algorithm>
#include <functional>
using namespace std;
class widget {
public:
widget(int id) : m_id(id) {}
private:
int m_id;
};
class findwidget {
public:
findwidget(widget* p) : m_widget(p) {}
bool operator()(widget* p) const {
return p == m_widget ? true : false;
}
widget* m_widget;
};
list<widget*> m_widgetList;
void push_back(widget* pi){
if(m_widgetList.empty()) {
m_widgetList.push_back(pi);
} else {
if(!std::for_each(m_widgetList.begin(), m_widgetList.end(), findwidget(pi)))
m_widgetList.push_back(pi);
}
}
int main(int argc, char* argv[])
{
widget w1(1);
push_back(&w1);
return 0;
}
The solution is : Dont use
std::for_each. Use any from the following (whatever suits your situation):std::findstd::find_ifstd::find_first_ofExample of
std::find:Note if you use
std::find, you don’t need thefindWidgetfunctor. After all, you’re comparing just the addresses (i.e the pointers).By the way, it seems that you want the list to contain unique elements, and don’t want to keep duplicates. If that is so, then you better consider:
std::setstd::setautomatically will handle the dupilcate elements. That is, you can do this:then it will insert
piinto the set if its not in it. And if its already containing it,insertwill not insert it into the set.