在C ++ STL中设置crbegin()和crend()函数

在本文中,我们将讨论C ++ STL中的set::crbegin()和set::crend()函数,以及它们的语法,工作原理和返回值。

C ++ STL中的设置是什么?

C ++ STL中的集合是必须按常规顺序具有唯一元素的容器。集必须具有唯一元素,因为元素的值标识该元素。一旦在集合容器中添加了值,以后就无法修改,尽管我们仍然可以删除或将值添加到集合中。集用作二进制搜索树。

设置了什么:: crbegin()?

crbegin()函数是C ++ STL中的内置函数,在<set>头文件中定义。crbegin()表示常量反向开始迭代器,意味着cbegin是常量开始迭代器的反向,换句话说,函数crbegin()将返回指向与该函数关联的set容器的最后一个元素的迭代器。像其他迭代器一样,它也可以用于修改集合。这可以仅用于遍历已设置的容器。

语法

constant_iterator name_of_set.crbegin();

参数

此函数不接受任何参数。

返回值

此函数返回指向设置容器最后一个元素的迭代器。

示例

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

设置了什么:: crend()

crend()函数是C ++ STL中的内置函数,在<set>头文件中定义。crend()表示常量反向迭代器,意味着常量常量迭代器的cend反向,换句话说,函数crend()将返回指向与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