Skip to content

Instantly share code, notes, and snippets.

@gmbeard
Created January 5, 2015 19:43
Show Gist options
  • Save gmbeard/23c77114cd4c1bc3103d to your computer and use it in GitHub Desktop.
Save gmbeard/23c77114cd4c1bc3103d to your computer and use it in GitHub Desktop.
Chaining std::bind to perform arbitrary searches of custom types using std::find_if
#include <iostream>
#include <functional>
#include <vector>
class Item
{
private:
std::string m_ItemId;
int m_Price;
int m_Count;
public:
Item(std::string const& id, int price, int count)
: m_ItemId{id},
m_Price{price},
m_Count{count}
{ }
int getCount() const
{ return m_Count; }
std::string const& getItemId() const
{ return m_ItemId; }
int getPrice() const
{ return m_Price; }
};
using ItemList = std::vector<Item>;
int main(int, char**)
{
using namespace std;
using namespace std::placeholders;
auto items = ItemList{};
items.emplace_back("D121", 100, 2);
items.emplace_back("D122", 12, 5);
items.emplace_back("D123", 28, 6);
items.emplace_back("D124", 8, 10);
items.emplace_back("D125", 99, 3);
auto result =
find_if(
begin(items),
end(items),
bind(equal_to<int>(), bind(&Item::getPrice, _1), 8)
);
cout << (*result).getItemId() << endl;
result =
find_if(
begin(items),
end(items),
bind(equal_to<string>(), bind(&Item::getItemId, _1), "D122")
);
cout << (*result).getPrice() << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment