C++ Set cend()函数
C++ set cend() 函数用于返回一个常量迭代器,该迭代器位于集合中最后一个元素之后。
注意:- 这是一个占位符,在这个位置上没有任何元素存在,尝试访问是未定义的行为。
语法
const_iterator cend() const noexcept;  //since C++ 11
const_iterator 是指向常量内容的迭代器。
参数
无
返回值
它返回一个常量迭代器,它指向set的最后一个元素之后。
复杂度
常数。
迭代器有效性
没有变化。
数据竞争
访问容器。
同时访问set的元素是安全的。
异常安全
该成员函数不会抛出异常。
示例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集合中最后一个元素之后的位置。
 极客笔记
极客笔记