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