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



描述

C++ 建構函式std::set::set()(初始化列表建構函式)使用初始化列表init的內容構造一個集合容器。

宣告

以下是來自std::set標頭檔案的std::set::set()初始化列表建構函式的宣告。

C++11

set (initializer_list<value_type> init,
     const key_compare& comp = key_compare(),
     const allocator_type& alloc = allocator_type());

C++14

set (initializer_list<value_type> init,
     const key_compare& comp = key_compare(),
     const allocator_type& alloc = allocator_type());
set (initializer_list<value_type> init,
     const allocator_type& alloc = allocator_type());

引數

  • alloc − 指向初始位置的輸入迭代器。

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

  • init − init 是一個初始化列表物件,它初始化集合容器元素。集合容器中存在的元素是value_type(成員型別)

返回值

建構函式不返回值。

異常

如果丟擲任何異常,此成員函式無效。

時間複雜度

一般情況下為N log(N),其中 N = init.size();

否則,線性時間複雜度 O(N),如果init已經排序。

示例

以下示例顯示了std::set::set()(初始化列表)建構函式的用法。

#include <iostream>
#include <set>
#include <string>

using namespace std;

int main() {
   // Initializer list constructor
   std::set<std::string> fruit {
      "orange", "apple", "mango", "peach", "grape"
   };

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

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

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