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


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

C++ multiset cend() 函數用於返回一個常量迭代器,該迭代器位於 multiset 中最後一個條目的旁邊。

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

用法

const_iterator cend() const noexcept;  //since C++ 11

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

參數

返回值

cend() 函數返回一個常量迭代器,它指向多集最後一個元素的旁邊。

複雜度

恒定。

迭代器有效性

沒有變化。

數據競爭

容器被訪問。

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

異常安全

這個成員函數從不拋出異常。

例子1

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

#include <iostream>
#include <set>

using namespace std;

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

  cout << "mymultiset contains:";
  for (auto it=mymultiset.cbegin(); it != mymultiset.cend(); ++it)
    cout << ' ' << *it;

  cout << '\n';

  return 0;
}

輸出:

mymultiset contains:10 10 20 20 30 40

在上麵的示例中,cend() 函數用於返回指向 mymultiset 多集中最後一個元素旁邊的迭代器。

例子2

讓我們看一個簡單的例子來查找多重集中的元素:

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

using namespace std;

int main ()
{
    int val;
    multiset<int> c = {10,20,30,30,20};
 
    cout<<"Enter value to find:";
    cin>>val;

    auto result = c.find(val);  
    
    //find until end of the multiset elements
    if (result != c.cend()) {  
        cout << "Element found:"<< *result; 
        cout << endl;  
    } else {  
        cout << "Element not found." << endl;  
    }  
    
  return 0;
}

輸出:

Enter value to find:10
Element found:10

例子3

讓我們看一個使用 while 循環遍曆多重集的簡單示例:

#include <iostream>
#include <set>
#include <string>
int main()
{
    using namespace std;
 
    multiset<string> mymultiset = {"Orange", "Banana", "Apple", "Orange"};

    multiset<string>::const_iterator it; // declare an iterator
    
    it = mymultiset.cbegin(); // assign it to the start of the multiset
    
    while (it != mymultiset.cend()) // while it hasn't reach the end
    {
        cout << *it <<endl; 
        // print the value of the element it points to
        ++it; // and iterate to the next element
    }
    cout << endl;
}

輸出:

Apple
Banana
Orange
Orange

在上麵的示例中,cend() 函數用於返回指向 mymultiset 多集中最後一個元素旁邊的迭代器。

示例 4

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

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

using namespace std;

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

  for_each(c.cbegin(), c.cend(), [](const int& x) {
    cout << x << endl;
  });
  
  return 0;
}

輸出:

1
1
2
3

在上麵的示例中,cend() 函數用於返回指向 mymultiset 多集中最後一個元素旁邊的迭代器。





相關用法


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