C++ set end() 函數用於返回集合中最後一個條目旁邊的迭代器。
注意:- 這是一個占位符。此位置不存在元素,嘗試訪問是未定義的行為。
用法
iterator end(); //until C++ 11
const_iterator end() const; //until C++ 11
iterator end() noexcept; //since C++ 11
const_iterator end() const noexcept; //since C++ 11
參數
空
返回值
它返回一個指向集合最後一個元素旁邊的迭代器。
複雜度
恒定。
迭代器有效性
沒有變化。
數據競爭
同時訪問集合的元素是安全的。
容器不會被訪問,非常量和常量版本都不會修改容器。
異常安全
此成員函數從不拋出異常。
例子1
讓我們看看 end() 函數的簡單示例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<string> myset = {"Java", "C++", "SQL"};
// show content:
for (set<string>::iterator it=myset.begin(); it!=myset.end(); ++it)
cout << *it<< '\n';
return 0;
}
輸出:
C++ Java SQL
在上麵的例子中, end() 函數用於返回指向 myset 集中最後一個元素旁邊的迭代器。
例子2
讓我們看一個使用 for-each 循環迭代集合的簡單示例:
#include <iostream>
#include <set>
using namespace std;
int main()
{
set<int> c;
c.insert(5);
c.insert(2);
c.insert(4);
c.insert(1);
c.insert(0);
c.insert(0);
c.insert(9);
set<int>::iterator i = c.begin();
while (i != c.end())
cout << *i++ << " ";
cout << endl;
}
輸出:
0 1 2 4 5 9
例子3
讓我們看一個使用 while 循環迭代集合的簡單示例:
#include <iostream>
#include <set>
#include <string>
int main()
{
using namespace std;
set<string> myset = { "Nikita","Deep","Priya","Suman","Aman" };
cout<<"Elements of myset are:"<<endl;
set<string>::const_iterator it; // declare an iterator
it = myset.begin(); // assign it to the start of the set
while (it != myset.end()) // while it hasn't reach the end
{
cout << *it << "\n";
// print the value of the element it points to
++it; // and iterate to the next element
}
cout << endl;
}
輸出:
Elements of myset are: Aman Deep Nikita Priya Suman
在上麵的例子中, end() 函數用於返回指向 myset 集中最後一個元素旁邊的迭代器。
示例 4
讓我們看一個簡單的例子:
#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.end()) {
cout << "Element found:"<< *result;
cout << endl;
} else {
cout << "Element not found." << endl;
}
return 0;
}
輸出:
Enter value to find:60 Element not found. Enter value to find:30 Element found:30
在上麵的例子中, end() 函數用於返回指向 myset 集中最後一個元素旁邊的迭代器。
相關用法
- C++ set erase()用法及代碼示例
- C++ set equal_range()用法及代碼示例
- C++ set emplace()用法及代碼示例
- C++ set empty()用法及代碼示例
- C++ set emplace_hint()用法及代碼示例
- C++ set rbegin()用法及代碼示例
- C++ set upper_bound()用法及代碼示例
- C++ set swap()用法及代碼示例
- C++ set size()用法及代碼示例
- C++ set lower_bound()用法及代碼示例
- C++ set find()用法及代碼示例
- C++ set cbegin()用法及代碼示例
- C++ set key_comp()用法及代碼示例
- C++ set rend()用法及代碼示例
- C++ set clear()用法及代碼示例
- C++ set begin()用法及代碼示例
- C++ set cbegin()、cend()用法及代碼示例
- C++ set count()用法及代碼示例
- C++ set max_size()用法及代碼示例
- C++ set crend()用法及代碼示例
注:本文由純淨天空篩選整理自 C++ set end()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。