C++ STL 中的 set::cbegin() 和 set::cend() 函式


在本文中,我們將討論 C++ STL 中的 set::cend() 和 set::cbegin() 函式,包括它們的語法、工作原理以及返回值。

什麼是 C++ STL 中的 Set?

C++ STL 中的 Set 是一種容器,它必須包含按一般順序排列的唯一元素。Set 必須包含唯一元素,因為元素的值標識了該元素。一旦將一個值新增到 Set 容器中,之後就不能修改它,儘管我們仍然可以從 Set 中刪除或新增值。Set 用作二叉搜尋樹。

什麼是 set::cbegin()?

cbegin() 函式是 C++ STL 中的一個內建函式,它在標頭檔案中定義。此函式返回一個常量迭代器,該迭代器指向 Set 容器中的第一個元素。由於 Set 容器中的所有迭代器都是常量迭代器,因此它們不能用於修改內容,我們只能使用它們透過增加或減少迭代器來遍歷 Set 容器中的元素。

語法

constant_iterator name_of_set.cbegin();

引數

This function does not accept any parameter.

返回值

此函式返回一個 constant_iterator,它指向序列的末尾。

示例

Input: set<int> set_a = {18, 34, 12, 10, 44};
   set_a.cbegin();
Output: Beginning element in the set container: 10

示例

即時演示

#include <iostream>
#include <set>
using namespace std;
int main (){
   set<int> set_a = {18, 34, 12, 10, 44};
   cout << "Beginning element in the set container: ";
   cout<< *(set_a.cbegin());
   return 0;
}

輸出

如果我們執行以上程式碼,則將生成以下輸出:

Beginning element in the set container: 10

示例

即時演示

#include <iostream>
#include <set>
using namespace std;
int main (){
   set<int> set_a = {18, 34, 12, 10, 44};
   cout << "set_a contains:";
   for (auto it=set_a.cbegin(); it != set_a.cend(); ++it)
      cout << ' ' << *it;
   cout << '\n';
   return 0;
}

輸出

如果我們執行以上程式碼,則將生成以下輸出:

set_a contains: 10 12 18 34 44

什麼是 set::cend()?

cend() 函式是 C++ STL 中的一個內建函式,它在標頭檔案中定義。此函式返回一個常量迭代器,該迭代器指向 Set 容器中最後一個元素之後的元素。由於 Set 容器中的所有迭代器都是常量迭代器,因此它們不能用於修改內容,我們只能使用它們透過增加或減少迭代器來遍歷 Set 容器中的元素。

語法

constant_iterator name_of_set.cend();

引數

此函式不接受任何引數。

返回值

此函式返回一個 constant_iterator,它指向序列的末尾。

示例

Input: set<int> set_a = {18, 34, 12, 10, 44};
set_a.end();
Output: Past to end element: 5

set::cend() 與 cbegin() 或 begin() 一起使用以遍歷整個 Set,因為它指向容器中最後一個元素之後的元素。

示例

即時演示

#include <iostream>
#include <set>
using namespace std;
int main (){
   set<int> set_a = {18, 34, 11, 10, 44};
   cout << "Past to end element: ";
   cout<< *(set_a.cend());
   return 0;
}

輸出

如果我們執行以上程式碼,則將生成以下輸出:

Past to end element: 5
We will get a random value

示例

即時演示

#include <iostream>
#include <set>
using namespace std;
int main (){
   set<int> set_a = {18, 34, 12, 10, 44};
   cout << " set_a contains:";
   for (auto it= set_a.cbegin(); it != set_a.cend(); ++it)
   cout << ' ' << *it;
   cout << '\n';
   return 0;
}

輸出

如果我們執行以上程式碼,則將生成以下輸出:

set_a contains: 10 12 18 34 44

更新於: 2020-03-05

182 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.