Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

C++ flat_set::begin() Function



The std::flat_set::begin() function in C++, is used to return an iterator pointing to the first element of the flat_set. A flat_set is a sorted container that stores unique elements in a flat structure, typically implemented using a vector.

The begin() function allows traversal of elements in a sorted order. It comes in two forms, the non-const version returning an iterator and a const version returning a const_iterator.

Syntax

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

iterator begin() noexcept;
or
const_iterator begin() const noexcept;

Parameters

It does not accepts any parameter.

Return Value

This function returns the iterator to the first element.

Example 1

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

#include <iostream>
#include <boost/container/flat_set.hpp>
int main() {
   boost::container::flat_set < int > x = {321,23,121};
   auto a = x.begin();
   if (a != x.end()) {
      std::cout << "Result : " << * a << std::endl;
   }
   return 0;
}

Output

Output of the above code is as follows −

Result : 23

Example 2

Consider the following example, where we are going to define the flat_set with the strings, and then the begin() is used to iterate over the set using the loop.

#include <iostream>
#include <boost/container/flat_set.hpp>
int main() {
   boost::container::flat_set < std::string > a = {"Welcome","Hi","Hello"};
   for (auto x = a.begin(); x != a.end(); ++x) {
      std::cout << * x << " ";
   }
   std::cout << std::endl;
   return 0;
}

Output

Output of the above code is as follows −

Hello Hi Welcome 

Example 3

In the following example, where we are going to use the begin() along with the cbegin() for comparison.

#include <iostream>
#include <boost/container/flat_set.hpp>
int main() {
   boost::container::flat_set < char > a = {'d','y','b'};
   auto x1 = a.begin();
   auto x2 = a.cbegin();
   if (x1 == x2) {
      std::cout << "Both points to the same element: " << * x1 << std::endl;
   }
   return 0;
}

Output

If we run the above code it will generate the following output −

Both points to the same element: b
cpp_flat_set.htm
Advertisements