當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ multiset crend()用法及代碼示例

C++ multiset crend() 函數用於以相反的順序返回一個常量迭代器到multiset的末尾(不是最後一個元素而是過去的最後一個元素)。這類似於非逆向容器的第一個元素之前的元素。

注意:- 這是一個占位符。此位置不存在元素,嘗試訪問是未定義的行為。

常量迭代器是指向常量內容的迭代器。

用法

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

參數

返回值

crend() 函數將 const_reverse_iterator 返回到反向容器的最後一個元素之後的元素。

複雜度

恒定。

迭代器有效性

沒有變化。

數據競爭

容器被訪問。

同時訪問多集容器的元素是安全的。

異常安全

此函數從不拋出異常。

例子1

讓我們看看 crend() 函數的簡單示例:

#include <iostream>
#include <set>

using namespace std;

int main ()
{
  multiset<int> mymultiset = {40,20,30,10,20};

  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 20 20 10

在上麵的例子中, crend() 函數用於返回一個常量反向迭代器到反向容器的最後一個元素之後的元素。

由於多重集以鍵的排序順序存儲元素,因此迭代多重集將導致上述順序,即鍵的排序順序。

例子2

讓我們看一個使用 while 循環以相反順序迭代多重集的簡單示例:

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

using namespace std;
 
int main() {
 
    // Creating & Initializing a multiset of String & Ints
    multiset<string> multisetEx = {"ccc", "bbb", "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;
}

輸出:

ccc
bbb
bbb
aaa

在上麵的例子中,我們以相反的順序在多重集上使用 while 循環到 const_iterate。

由於多重集以鍵的排序順序存儲元素,因此迭代多重集將導致上述順序,即鍵的排序順序。

例子3

讓我們看一個簡單的例子:

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

using namespace std;

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

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

輸出:

3
2
2
1

在上麵的例子中,multiset 的元素以相反的順序返回。

示例 4

讓我們看一個簡單的例子來排序和計算最高分:

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

using namespace std;

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

   cout << "Salary"<< '\n';
   cout<<"______________________\n";
   
  multiset<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
2500
2500
1200
1000

Highest salary:4500

在上麵的例子中,實現了一個 multiset emp,其中salary 被存儲為key。這使我們能夠利用 multiset 中薪水的自動排序,並讓我們識別最高薪水。





相關用法


注:本文由純淨天空篩選整理自 C++ multiset crend()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。