std::contains algorithm

739 views
Skip to first unread message

kern...@gmail.com

unread,
Nov 4, 2018, 5:38:47 PM11/4/18
to ISO C++ Standard - Future Proposals
std::set has a find member function. This member function uses the nature of a set to achieve O(log n) complexity. There exists a std::find algorithm that can be used with any container and has a complexity of O(n).

C++20 added a contains member function to some containers. Once again, the contains member function of std::set uses the nature of a set to achieve O(log n) complexity. However, there isn't (to my knowledge) a generic std::contains algorithm for containers that don't have a contains member function.

Personally, the absence of std::contains seems like an oversight. Is it?

Arthur O'Dwyer

unread,
Nov 5, 2018, 9:21:58 PM11/5/18
to ISO C++ Standard - Future Proposals, kern...@gmail.com
The point of .contains(), I think, is to be able to write

    if (myset.contains("foo")) { do a thing; }
    if (mymap.contains("foo")) { do a thing; }
    if (myvector.contains("foo")) { do a thing; }  // whoops, this doesn't exist in C++2a yet!

I wouldn't want to write

    if (std::contains(myvector.begin(), myvector.end(), "foo")) { do a thing; }

using a generic algorithm like that. That's just super verbose. I'd rather write a helper function

    if (my::contains(myvector, "foo")) { do a thing; }

in which case the existence of a generic range-based algorithm in std:: wouldn't help me at all, because I could just as easily implement `my::contains` in terms of the already-existing std::find as in terms of the hypothetical std::contains.

my $.02,
–Arthur

kern...@gmail.com

unread,
Nov 5, 2018, 10:09:01 PM11/5/18
to ISO C++ Standard - Future Proposals
I agree. Writing my::contains is trivial. However, you raised one of my criticisms of the standard algorithms. The verbosity. Every time I use a standard algorithm, I have to wrap the call into multiple lines (I don't like to go over 80 characters). Its ugly!

The only way to clean up the call site is to create helper functions like you suggested.

I used to think the Ranges TS will let me do this:
std::find(myvec.range(), "foo")
but then I actually read about Ranges and I was kind of disappointed.

peter...@gmail.com

unread,
Nov 7, 2018, 4:22:23 AM11/7/18
to ISO C++ Standard - Future Proposals, kern...@gmail.com
In Ranges TS you can do
    std::find(myvec, "foo")
which is even less verbose than what you hoped for.

kern...@gmail.com

unread,
Nov 7, 2018, 6:40:04 AM11/7/18
to ISO C++ Standard - Future Proposals, kern...@gmail.com, peter...@gmail.com
It looks like I misread something. Yep, you're right. Ranges are gonna be great! std::contains makes much more sense with Ranges. Maybe it makes sense to add std::contains after all.
Reply all
Reply to author
Forward
0 new messages