C++ Set crbegin()
C++ Set crbegin()
C++ Set crbegin()函数用于返回常量反向迭代器,该迭代器引用set容器中的最后一个元素
set的常量反向迭代器沿相反的方向移动并递增,直到到达set容器的开头(第一个元素)并指向 constant 元素。
语法
const_reverse_iterator crbegin() const noexcept; //since C++ 11
参数
无
返回值
它返回指向最后一个元素的常量反向迭代器
参数
无
返回值
它返回一个常量反向迭代器,指向多图的最后一个元素。
复杂度
常量。
迭代器有效性
没有更改。
数据竞争
可以访问容器。
同时访问集合的元素是安全的。
异常安全
此函数从不抛出异常。
示例1
让我们看看crbegin()函数的简单示例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<int> myset = {50,20,40,10,30};
cout << "myset in reverse order:";
for (auto rit=myset.crbegin(); rit != myset.crend(); ++rit)
cout << ' ' << *rit;
cout << '\n';
return 0;
}
输出:
myset in reverse order: 50 40 30 20 10
在上面的示例中,使用crbegin()函数返回一个常数反向迭代器,该迭代器指向myset集合中的最后一个元素。
因为set按键的排序顺序存储元素,遍历一个集合将导致以上顺序,即键的排序顺序。
示例2
让我们看一个简单的示例,该示例使用以下步骤以相反的顺序遍历该集合: while循环:
#include <iostream>
#include <set>
#include <string>
#include <iterator>
using namespace std;
int main() {
// Creating & Initializing a set of String & Ints
set<string> setEx = {"bbb", "ccc", "aaa", "ddd"};
// Create a set iterator and point to the end of set
set<string>::const_reverse_iterator it = setEx.crbegin();
// Iterate over the set using Iterator till beginning.
while (it != setEx.crend()) {
// Accessing KEY from element pointed by it.
string word = *it;
cout << word << endl;
// Increment the Iterator to point to next entry
it++;
}
return 0;
}
输出:
在上面的示例中,我们使用while循环以相反的顺序对集合进行const_iterate,并使用crbegin()函数初始化集合的最后一个元素。
因为集合按排序顺序存储元素因此,对一组键进行迭代将导致上述顺序,即键的排序顺序。
示例3
让我们看一个简单的示例来获取第一个元素的反向集:
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main ()
{
set<int> s1 = {20,40,10,30};
auto ite = s1.crbegin();
cout << "The first element of the reversed set s1 is: ";
cout << *ite;
return 0;
}
输出:
The first element of the reversed set s1 is: 40
在上面的示例中,crbegin()函数返回反向集s1的第一个元素,即40。
示例4
让我们看一个简单的例子排序和计算最高分数的示例:
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main ()
{
set<int> marks = {400, 220, 300, 250, 365};
cout << "Marks" << " | " << "Roll Number" << '\n';
cout<<"______________________\n";
set<int>::const_reverse_iterator rit;
for (rit=marks.crbegin(); rit!=marks.crend(); ++rit)
cout << *rit<< '\n';
auto ite = marks.crbegin();
cout << "\nHighest Marks is: "<< *ite<<" \n";
return 0;
}
输出:
Marks | Roll Number
______________________
400
365
300
250
220
Highest Marks is: 400
在上面的示例中,实现了一个集合标记,其中该集合的元素存储为键。函数crbegin()使我们能够利用集合中的自动排序功能,并识别最高分。