📜  C++ STL-Set.crbegin()函数

📅  最后修改于: 2020-10-20 07:52:51             🧑  作者: Mango

C++ STL Set.crbegin()

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

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

句法

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

参数

没有

返回值

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

参数

没有

返回值

它返回一个常数反向迭代器,该迭代器指向多图的最后一个元素。

复杂度

不变。

迭代器有效性

没有变化。

数据竞争

容器被访问。

同时访问集合的元素是安全的。

异常安全

此函数从不抛出异常。

例子1

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

#include 
#include 

using namespace std;

int main ()
{
  set 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因此按键的排序顺序存储元素,所以对set进行迭代将导致上述顺序,即键的排序顺序。

例子2

让我们看一个简单的示例,使用while循环以相反的顺序遍历集合:

#include 
#include 
#include 
#include 

using namespace std;
 
int main() {
 
    // Creating & Initializing a set of String & Ints
    set setEx = {"bbb", "ccc", "aaa", "ddd"};

    // Create a set iterator and point to the end of set
     set::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()函数初始化集合的最后一个元素。

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

例子3

让我们看一个简单的示例,以获取反转集的第一个元素:

#include 
#include 
#include 

using namespace std;

int main ()
{
  set 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 
#include 
#include 

using namespace std;

int main ()
{
  set marks = {400, 220, 300, 250, 365};

   cout << "Marks" << " | " << "Roll Number" << '\n';
   cout<<"______________________\n";
   
  set::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()使我们能够利用集合中的自动排序功能,并识别最高分。