C++ set cend() 使用方法及示例

C++ STL Set(集合)

C ++ set cend()函數(shù)用于返回一個常量迭代器,該迭代器位于集合中最后一個元素的旁邊。

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

語法

const_iterator cend() const noexcept;  //從 C++ 11開始

一個常量性是一個迭代器,它指向含量恒定。

參數(shù)

沒有

返回值

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

復雜

不變。

迭代器有效性

沒有變化。

數(shù)據(jù)競賽

容器被訪問。

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

異常安全

該成員函數(shù)從不拋出異常。

實例1

讓我們看一下cend()函數(shù)的簡單示例:

#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()函數(shù)用于返回指向myset集合中最后一個元素旁邊的迭代器。

實例2

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

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

using namespace std;

int main ()
{
    int val;
    set<int> c = {10,20,30,40,50};
 
    cout<<"輸入值以查找: ";
    cin>>val;

    auto result = c.find(val);  
    
    //查找直到set元素的結尾
    if (result != c.cend()) {  
        cout << "找到元素: "<< *result; 
        cout << endl;  
    } else {  
        cout << "未找到元素。" << endl;  
    }  
    
  return 0;
}

輸出:

輸入值以查找: 10
找到元素: 10

實例3

讓我們看一個簡單的示例,使用while循環(huán)遍歷集合:

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

    set<string>::const_iterator it; // 聲明一個迭代器
    
    it = myset.cbegin(); // 將其分配給集合的開始
    
    while (it != myset.cend())
    {
        cout << *it <<endl; 
        // 打印它所指向的元素的值
        ++it; // 并迭代到下一個元素
    }
    cout << endl;
}

輸出:

Apple
Banana
Orange

在上面的示例中,cend()函數(shù)用于返回指向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()函數(shù)用于返回指向myset集合中最后一個元素旁邊的迭代器。

C++ STL Set(集合)

丰满人妻一级特黄a大片,午夜无码免费福利一级,欧美亚洲精品在线,国产婷婷成人久久Av免费高清