C++ STL 中的 set::crbegin() 和 set::crend() 函式


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

什麼是 C++ STL 中的 Set?

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

什麼是 set::crbegin()?

crbegin() 函式是 C++ STL 中的一個內建函式,定義在 <set> 標頭檔案中。crbegin() 代表常量反向起始迭代器,也就是常量起始迭代器 (cbegin) 的反向版本。換句話說,crbegin() 函式將返回一個指向 Set 容器中最後一個元素的迭代器。與其他迭代器一樣,它也可用於遍歷 Set 容器,但不能修改 Set 的內容。

語法

constant_iterator name_of_set.crbegin();

引數

此函式不接受任何引數。

返回值

此函式返回一個指向 Set 容器中最後一個元素的迭代器。

示例

Input: set<int> myset = {1, 2, 3, 4, 5};
   myset.crbegin();
Output: 5

示例

線上演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   int arr[] = {1, 2, 3, 4, 5};
   set<int> ch(arr, arr + 5);
   for (auto i = ch.crbegin(); i!= ch.crend(); i++)
      cout << *i << " ";
   return 0;
}

輸出

如果執行上述程式碼,將生成以下輸出

5 4 3 2 1

什麼是 set::crend()

crend() 函式是 C++ STL 中的一個內建函式,定義在 <set> 標頭檔案中。crend() 代表常量反向結束迭代器,也就是常量結束迭代器 (cend) 的反向版本。換句話說,crend() 函式將返回一個指向 Set 容器中第一個元素之前位置的迭代器。與其他迭代器一樣,它也可用於遍歷 Set 容器,但不能修改 Set 的內容。

語法

constant_iterator name_of_set.crend();

引數

此函式不接受任何引數。

返回值

此函式返回一個指向 Set 容器中第一個元素之前位置的迭代器。

示例

Input: set<int> myset = {1, 2, 3, 4, 5};
myset.crend();
Output: 9 //random number before the first element in the set container.

示例

線上演示

#include <bits/stdc++.h>
using namespace std;
int main(){
   int arr[] = {3, 5, 8, 1, 9};
   set<int> ch(arr, arr + 5);
   for(auto i = ch.crbegin(); i!= ch.crend(); i++)
      cout << *i<< " ";
   return 0;
}

輸出

如果執行上述程式碼,將生成以下輸出

9 8 5 3 1

更新於:2020年3月5日

99 次瀏覽

開啟你的職業生涯

完成課程獲得認證

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