i have been trying figure out best way find object in vector. attempting use find on object:
class category { public: string modetype; vector<videomode> videomodes; category(){} category(string name) { modetype = name; } friend bool operator== ( const category &c1, const string &c2 ) { return c1.modetype == c2; } }; and find:
vector<category>::iterator category = find(modes.begin(), modes.end(), category("name")); i getting error when try compile saying there "no operator found takes left-hand operand of type "category" "==" looked algorithm header , found find code:
template<class _init, class _ty> inline _init _find(_init _first, _init _last, const _ty& _val) { // find first matching _val (; _first != _last; ++_first) if (*_first == _val) break; return (_first); } i not sure go here though. advise appreciated, don't know c++ :(
you've defined operator== take category , std::string, you're trying find category, operator== not defined for. in case, could pass string literal:
find(modes.begin(), modes.end(), "name") however, suggest changing equality operator take category. comparing 2 objects of same type logical, , way works when string on left without overload, since type implicitly convertible std::string. suggest not making friend since doesn't access more public members:
bool operator==(const category &lhs, const category &rhs) { return lhs.modetype == rhs.modetype; } to use std::find work way have it, not if pass string literal. because have go through 2 user-defined conversions reach class (std::string class), 1 can performed. keeping overloads down, nicest solution once c++14 comes along make use of new literal suffixes:
find(modes.begin(), modes.end(), "name"s) ^std::string because of s for now, it's possible define own _s same. prefer user adding s or _s putting in 2 more overloads or overloading constructor take types std::string constructible from. feels pointless work , increases possibility of ambiguity.
Comments
Post a Comment