C ++ set cend()函數(shù)用于返回一個常量迭代器,該迭代器位于集合中最后一個元素的旁邊。
const_iterator cend() const noexcept; //從 C++ 11開始
一個常量性是一個迭代器,它指向含量恒定。
沒有
它返回一個常量迭代器,該迭代器指向該集合的最后一個元素。
不變。
沒有變化。
容器被訪問。
同時訪問集合的元素是安全的。
該成員函數(shù)從不拋出異常。
讓我們看一下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集合中最后一個元素旁邊的迭代器。
讓我們看一個簡單的示例來查找集合中的元素:
#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
讓我們看一個簡單的示例,使用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集合中最后一個元素旁邊的迭代器。
讓我們看一個簡單的實例:
#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集合中最后一個元素旁邊的迭代器。