C++ Set 中的 Cend函数

首页 / C++入门教程 / C++ Set 中的 Cend函数

C++ set cend()函数用于返回常量迭代器,该常量迭代器位于set中的最后一个条目旁边。

Note:- 这是一个占位符。此位置没有元素,尝试访问是未定义的行为。

Cend - 语法

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

const_iterator 是指向常量内容的迭代器。

Cend - 返回值

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

Cend - 例子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集合中最后一个元素旁边的迭代器。

Cend - 例子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

Cend - 例子3

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

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-set-cend-function.html

来源:LearnFk无涯教程网

#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集合中最后一个元素旁边的迭代器。

Cend - 例子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集合中最后一个元素旁边的迭代器。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

Serverless入门课 -〔蒲松洋(秦粤)〕

视觉笔记入门课 -〔高伟〕

分布式数据库30讲 -〔王磊〕

React Hooks 核心原理与实战 -〔王沛〕

数据分析思维课 -〔郭炜〕

大数据经典论文解读 -〔徐文浩〕

深入剖析Java新特性 -〔范学雷〕

网络排查案例课 -〔杨胜辉〕

LangChain 实战课 -〔黄佳〕

好记忆不如烂笔头。留下您的足迹吧 :)