C++ 集合庫 - set() 函式



描述

C++ 建構函式std::set::set()(範圍建構函式)使用[first,last)範圍內提到的元素數量構造一個集合容器,每個集合元素都由該範圍內對應的元素構造。

宣告

以下是來自std::set標頭檔案的std::set::set()範圍建構函式的宣告。

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());

引數

  • alloc - 輸入迭代器到初始位置。

  • comp - 用於所有鍵比較的比較函式物件

  • first, last - 要從中複製的範圍,它們是輸入迭代器。此範圍包括從first到last的元素,包括first指向的元素,但不包括last指向的元素。

返回值

建構函式從不返回值。

異常

如果丟擲任何異常,此成員函式無效。但是,如果[first,last)指定的範圍無效,則可能導致未定義的行為。

時間複雜度

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

否則在迭代器之間的距離上是線性的 (O(N)),如果元素已排序。

示例

以下示例顯示了std::set::set()範圍建構函式的使用。

#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;
}

讓我們編譯並執行上述程式,這將產生以下結果:

Size of set container t_set is : 5
set.htm
廣告