C++ Set 中的 crbegin函数

首页 / C++入门教程 / C++ Set 中的 crbegin函数

C++ set crbegin()函数用于返回一个常量反向迭代器,该迭代器引用set集合中的最后一个元素。

set的常量反向迭代器沿反向移动并递增,直到到达set集合的开头(第一个元素)并指向 constant 元素。

crbegin - 语法

const_reverse_iterator crbegin() const noexcept;  	      //since C++ 11

crbegin - 返回值

它返回一个常量反向迭代器,该迭代器指向集合的最后一个元素。

crbegin - 例子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集合中的最后一个元素。

因为集合因此按键的排序顺序存储元素,所以对集合进行迭代将导致上述顺序,即键的排序顺序。

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-set-crbegin-function.html

来源:LearnFk无涯教程网

crbegin - 例子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;
}

输出:

ddd
ccc
bbb
aaa

在上面的示例中,我们使用while循环以相反的顺序对集合进行const_iterate,并使用crbegin()函数初始化集合的最后一个元素。

无涯教程网

因为集合因此按键的排序顺序存储元素,所以对集合进行迭代将导致上述顺序,即键的排序顺序。

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-set-crbegin-function.html

来源:LearnFk无涯教程网

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。

crbegin - 例子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

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

iOS开发高手课 -〔戴铭〕

Java性能调优实战 -〔刘超〕

Node.js开发实战 -〔杨浩〕

Netty源码剖析与实战 -〔傅健〕

编译原理实战课 -〔宫文学〕

Flink核心技术与实战 -〔张利兵〕

说透元宇宙 -〔方军〕

人人都用得上的数字化思维课 -〔付晓岩〕

Python实战 · 从0到1搭建直播视频平台 -〔Barry〕

好记忆不如烂笔头。留下您的足迹吧 :)