C++ multiset cend()
C++ multiset cend()
C++ multiset cend()函数用于返回常量迭代器,该迭代器位于 multiset 中最后一个条目的旁边
注意: 注意:-这是一个占位符。此位置没有元素,尝试访问是未定义的行为。
语法
const_iterator cend() const noexcept; //since C++ 11
const_iterator 是指向常量内容的迭代器。
参数
无
返回值
cend()函数返回一个常量迭代器,该迭代器指向 multiset 的最后一个元素。
复杂度
常量。
迭代器有效性
无变化。
数据竞争
访问容器。
同时访问 multiset 容器的元素是安全的。
异常安全性
此成员函数永远不会
示例1
让我们看一下cend()函数的简单示例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
multiset<int> mymultiset = {20,20,30,40,10,10};
cout << "mymultiset contains:";
for (auto it=mymultiset.cbegin(); it != mymultiset.cend(); ++it)
cout << ' ' << *it;
cout << '\n';
return 0;
}
输出:
mymultiset contains: 10 10 20 20 30 40
在上面的示例中,cend()函数用于返回指向mymultiset multiset 中的最后一个元素旁边的迭代器。
示例2
让我们看一个简单的示例来查找 multiset 中的元素:
#include <iostream>
#include <string>
#include <set>
using namespace std;
int main ()
{
int val;
multiset<int> c = {10,20,30,30,20};
cout<<"Enter value to find: ";
cin>>val;
auto result = c.find(val);
//find until end of the multiset 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循环遍历 multiset 的简单示例:
#include <iostream>
#include <set>
#include <string>
int main()
{
using namespace std;
multiset<string> mymultiset = {"Orange", "Banana", "Apple", "Orange"};
multiset<string>::const_iterator it; // declare an iterator
it = mymultiset.cbegin(); // assign it to the start of the multiset
while (it != mymultiset.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
Orange
在上面的示例中,cend()函数用于返回指向mymultiset multiset 中的最后一个元素旁边的迭代器。
示例4
让我们看一个简单的例子:
#include <iostream>
#include <set>
#include <algorithm>
using namespace std;
int main()
{
multiset<int> c = {3, 1, 2, 1};
for_each(c.cbegin(), c.cend(), [](const int& x) {
cout << x << endl;
});
return 0;
}
输出:
在上面的示例中,cend()函数用于返回指向mymultiset multiset 中最后一个元素旁边的迭代器。