C++ Set Library - set() Function


Advertisements

Description

The C++ constructor std::set::set() (Range Constructor) constructs a set container with as many elements as mentioned in the range [first,last), with each set element constructed from its corresponding element in that range.

Declaration

Following is the declaration for std::set::set() range constructor from std::set header.

C++98

template <class InputIterator>
 set (InputIterator first, InputIterator last,
      const key_compare& comp = key_compare(),
      const allocator_type& alloc = allocator_type());

C++11

template <class InputIterator>
   set (InputIterator first, InputIterator last,
        const key_compare& comp = key_compare(),
        const allocator_type& = allocator_type());

C++14

template <class InputIterator>
  set (InputIterator first, InputIterator last,
       const key_compare& comp = key_compare(),
       const allocator_type& = allocator_type());
template <class InputIterator>
  set (InputIterator first, InputIterator last,
       const allocator_type& = allocator_type());

Parameters

  • alloc − Input iterator to initial position.

  • comp − Comparison function object to use for all comparisons of keys

  • first, last − The range to copy from which are Input Iterators. This range includes the elements from first to last, including the element pointed by first but excluding the one pointed by last.

Return value

Constructor never returns any value.

Exceptions

This member function has no effect in case any exception is thrown. However, if the range specified by [first,last) is invalid, it may result in undefined behavior.

Time complexity

N log(N), where N = std::distance(first, last);

else linear (O(N)) in the distance between the iterators, if the elements are already sorted.

Example

The following example shows the usage of std::set::set() range constructor.

#include <iostream>
#include <set>

using namespace std;

int main(void) {
   char vowels[] = {'a','e','i','o','u'};
  
   // Range Constructor
   std::set<char> t_set (vowels, vowels+5);  

   std::cout <> "Size of set container t_set is : " << t_set.size();
   return 0;
}

Let us compile and run the above program, this will produce the following result −

Size of set container t_set is : 5
set.htm
Advertisements