C++ flat_set::find() Function



The std::flat_set::find() function in C++, is used to search for a specific element within a flat_set. If the element is found, it returns an iterator pointing to it, orelse it returns an iterstor to the end of the set.

Unlike, std::set, flat_set stores the elements in the sorted vector-like structure, providing efficient memory usage and cache locality. The time complexity of this function is O(log n).

Syntax

Following is the syntax for std::flat_set::find() function.

 iterator find( const Key& key ); or const_iterator find( const Key& key ) const; 

Parameters

  • key − It indicates the key value of the element to search for.

Return Value

This function returns an iterator to the requested element.

Example 1

Let's look at the following example, where we are going to consider the basic usage of the find() function.

 #include <iostream> #include <boost/container/flat_set.hpp> int main() { boost::container::flat_set < int > a = {12,23,34,45}; auto x = a.find(23); if (x != a.end()) { std::cout << "Element Found: " << * x << std::endl; } else { std::cout << "Element Not Found" << std::endl; } return 0; } 

Output

Output of the above code is as follows −

 Element Found: 23 

Example 2

Consider the following example, where we are going to search for the element that does not exist and observing the output.

 #include <iostream> #include <boost/container/flat_set.hpp> int main() { boost::container::flat_set < int > a = {1,3,5}; auto x = a.find(2); if (x != a.end()) { std::cout << "Element Found: " << * x << std::endl; } else { std::cout << "Element Not Found" << std::endl; } return 0; } 

Output

Following is the output of the above code −

 Element Not Found 
cpp_flat_set.htm
Advertisements