3 ms·
I wish C++ had a isMember method for its containers or a keyword like Python's "in". The most succinct way to do this currently (with vector for instance) vect
by rodly 14y ago
I wish C++ had a isMember method for its containers or a keyword like Python's "in". The most succinct way to do this currently (with vector for instance)
vector<string> naughtyList {"Bob", "Tom", "Rod", "God"};
string member = "Jerry";
for (string & each : naughtyList)
if (member == each)
// do stuff
/rant
- benhoyt 14y agoI'm not sure why "find" or "contains" isn't a member function of STL container types, but there is the std::find() function: bool xIsMember = std::find(v.begin(), v.end(), x) != v.end(); Edit: I admit this is terrible API design. When you want the v.begin()/v.end() combination 90% of the time, why not at least have a std::find() overload that does that for you? Or simply add "std::contains(v, x) -> bool"? You can write your own version of that, of course, but... my take-home point: API design is very important.
- awnird 14y agoProviding container operations as functions in <algorithm> operating on iterators means that someone implementing a new container with iterators immediately has a wealth of functionality available with no extra effort. Also, containers that are most well suited to membership searches (std::set and std::multiset) do include find(Key const& key) as a member.