當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ Set set()用法及代碼示例


描述

C++ 構造函數std::set::set()(Range Constructor) 構造一個集合容器,其中包含與範圍 [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

相關用法


注:本文由純淨天空篩選整理自 C++ Set Library - set() Function。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。