C++ set cend()函数用于返回常量迭代器,该常量迭代器位于set中的最后一个条目旁边。
const_iterator cend() const noexcept; //since C++ 11
const_iterator 是指向常量内容的迭代器。
它返回一个常量迭代器,该迭代器指向该集合的最后一个元素。
让我们看一下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集合中最后一个元素旁边的迭代器。
让我们看一个简单的示例来查找集合中的元素:
#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
让我们看一个简单的示例,使用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集合中最后一个元素旁边的迭代器。
让我们看一个简单的例子:
#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集合中最后一个元素旁边的迭代器。
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)