C ++ set cend()函数用于返回一个常量迭代器,该迭代器位于集合中最后一个元素的旁边。
const_iterator cend() const noexcept; //从 C++ 11开始
一个常量性是一个迭代器,它指向含量恒定。
没有
它返回一个常量迭代器,该迭代器指向该集合的最后一个元素。
不变。
没有变化。
容器被访问。
同时访问集合的元素是安全的。
该成员函数从不抛出异常。
让我们看一下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<<"输入值以查找: ";
cin>>val;
auto result = c.find(val);
//查找直到set元素的结尾
if (result != c.cend()) {
cout << "找到元素: "<< *result;
cout << endl;
} else {
cout << "未找到元素。" << endl;
}
return 0;
}输出:
输入值以查找: 10 找到元素: 10
让我们看一个简单的示例,使用while循环遍历集合:
#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()函数用于返回指向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集合中最后一个元素旁边的迭代器。