Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check that an element is in a std::set?

How do you check that an element is in a set?

Is there a simpler equivalent of the following code:

myset.find(x) != myset.end() 
like image 790
fulmicoton Avatar asked Nov 09 '09 13:11

fulmicoton


People also ask

What is std :: set?

std::set is an associative container that contains a sorted set of unique objects of type Key . Sorting is done using the key comparison function Compare. Search, removal, and insertion operations have logarithmic complexity. Sets are usually implemented as red-black trees.

What is set in C++?

Sets are a type of associative container in which each element has to be unique because the value of the element identifies it. The values are stored in a specific sorted order i.e. either ascending or descending.


2 Answers

The typical way to check for existence in many STL containers such as std::map, std::set, ... is:

const bool is_in = container.find(element) != container.end(); 
like image 75
unwind Avatar answered Oct 13 '22 18:10

unwind


Another way of simply telling if an element exists is to check the count()

if (myset.count(x)) {    // x is in the set, count is 1 } else {    // count zero, i.e. x not in the set } 

Most of the times, however, I find myself needing access to the element wherever I check for its existence.

So I'd have to find the iterator anyway. Then, of course, it's better to simply compare it to end too.

set< X >::iterator it = myset.find(x); if (it != myset.end()) {    // do something with *it } 

C++ 20

In C++20 set gets a contains function, so the following becomes possible as mentioned at: https://stackoverflow.com/a/54197839/895245

if (myset.contains(x)) {   // x is in the set } else {   // no x  } 
like image 44
Pieter Avatar answered Oct 13 '22 18:10

Pieter