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


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

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

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

用法

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

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

參數

返回值

它返回一個常量迭代器,它指向集合的最後一個元素旁邊。

複雜度

恒定。

迭代器有效性

沒有變化。

數據競爭

容器被訪問。

同時訪問集合的元素是安全的。

異常安全

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

例子1

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

#include <iostream>
#include <set>

int main ()
{
  std::set<int> myset = {60,20,40,50,10,30};

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

  std::cout << '\n';

  return 0;
}

輸出:

myset contains:10 20 30 40 50 60

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

例子2

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

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

using namespace std;

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

    auto result = c.find(val);  
    
    //find until end of the set 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;
 
    set<string> myset = {"Orange", "Banana", "Apple"};

    set<string>::const_iterator it; // declare an iterator
    
    it = myset.cbegin(); // assign it to the start of the set
    
    while (it != myset.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

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

示例 4

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

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

using namespace std;

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

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

輸出:

1
2
3

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






相關用法


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