C++ Set 中的 Crend函数

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

C++ set crend()函数用于以反向顺序将常量迭代器返回到集合的末尾(不是最后一个元素,而是过去的最后一个元素) 。这类似于非反转集合的第一个元素之前的元素。

Note:-这是一个占位符。此位置没有元素,尝试访问是未定义的行为。

Crend - 语法

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

Crend - 返回值

它将const_reverse_iterator返回到反转集合的最后一个元素之后的元素。

Crend - 例子1

让我们看一下crend()函数的简单示例:

#include <iostream>
#include <set>

using namespace std;

int main ()
{
  set<int> myset = {40,20,50,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

在上面的示例中,crend()函数用于将常量反向迭代器返回到反向集合最后一个元素之后的元素。

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

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

来源:LearnFk无涯教程网

Crend - 例子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 = {"ccc", "ddd", "aaa", "bbb"};
 
	// 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。

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

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

来源:LearnFk无涯教程网

Crend - 例子3

让我们看一个简单的例子:

#include <iostream>
#include <set>
#include <algorithm>

using namespace std;

int main()
{
  set<int> c = {3, 1, 2};

  for_each(c.crbegin(), c.crend(), [](const int& x) {
    cout << x << endl;
  });
}

输出:

3
2
1

在上面的示例中,set的元素以相反的顺序返回。

Crend - 例子4

让我们看一个简单的示例来对最高分进行排序和计算:

#include <iostream>
#include <string>
#include <set>

using namespace std;

int main ()
{
  set<int> emp = {1000,2500,4500,1200,3000};

   cout << "Salary"<< '\n';
   cout<<"______________________\n";
   
  set<int>::const_reverse_iterator rit;
  for (rit=emp.crbegin(); rit!=emp.crend(); ++rit)
    cout << *rit<< '\n';

    auto ite = emp.crbegin();
 
    cout << "\nHighest salary: "<< *ite <<" \n";

  return 0;
  }

输出:

Salary
______________________
4500
3000
2500
1200
1000

Highest salary: 4500 

在上面的示例中,实现了一个set emp,其中薪水存储为键。这使我们能够利用工资的自动排序函数,并确定最高工资。

无涯教程网

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

技术教程推荐

MySQL实战45讲 -〔林晓斌〕

说透中台 -〔王健〕

打造爆款短视频 -〔周维〕

玩转Vue 3全家桶 -〔大圣〕

反爬虫兵法演绎20讲 -〔DS Hunter〕

说透低代码 -〔陈旭〕

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

快手 · 移动端音视频开发实战 -〔展晓凯〕

云时代的JVM原理与实战 -〔康杨〕

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