C ++ set end()函數(shù)的作用是:返回一個(gè)迭代器,該迭代器位于集合的最后一個(gè)元素的旁邊。
iterator end(); //直到 C ++ 11 const_iterator end() const; //直到 C ++ 11 iterator end() noexcept; //從 C++ 11開始 const_iterator end() const noexcept; //從 C++ 11開始
沒有
它返回一個(gè)迭代器,該迭代器指向集合的最后一個(gè)元素。
不變。
沒有變化。
同時(shí)訪問集合的元素是安全的。
無論是非const版本還是const版本都不能訪問該容器。
該成員函數(shù)永遠(yuǎn)不會(huì)引發(fā)異常。
讓我們看一下end()函數(shù)的簡(jiǎn)單示例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<string> myset = {"Java", "C++", "SQL"};
// 顯示內(nèi)容:
for (set<string>::iterator it=myset.begin(); it!=myset.end(); ++it){
cout << *it<< '\n';
}
return 0;
}輸出:
C++ Java SQL
在上面的示例中,end()函數(shù)用于返回指向myset集合中最后一個(gè)元素旁邊的迭代器。
讓我們看一個(gè)簡(jiǎn)單的示例,使用for-each循環(huán)遍歷集合:
#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
讓我們看一個(gè)簡(jiǎn)單的示例,使用while循環(huán)遍歷集合:
#include <iostream>
#include <set>
#include <string>
int main()
{
using namespace std;
set<string> myset = { "Nikita","Deep","Priya","Suman","Aman" };
cout<<"myset的元素是: "<<endl;
set<string>::const_iterator it; // 聲明一個(gè)迭代器
it = myset.begin(); // 將其分配給集合的開始
while (it != myset.end())
{
cout << *it << "\n";
// 打印它所指向的元素的值
++it; // 并迭代到下一個(gè)元素
}
cout << endl;
}輸出:
myset的元素是: Aman Deep Nikita Priya Suman
在上面的示例中,end()函數(shù)用于返回指向myset集合中最后一個(gè)元素旁邊的迭代器。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#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元素的結(jié)尾
if (result != c.end()) {
cout << "Element found: "<< *result;
cout << endl;
} else {
cout << "未找到元素。" << endl;
}
return 0;
}輸出:
輸入值以查找: 60 未找到元素。 輸入值以查找: 30 Element found: 30
在上面的示例中,end()函數(shù)用于返回指向myset集合中最后一個(gè)元素旁邊的迭代器。