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