C ++ set begin()函數(shù)用于返回引用set容器的第一個(gè)元素的迭代器。
iterator begin(); //直到 C ++ 11 const_iterator begin() const; //直到 C ++ 11 iterator begin() noexcept; //從 C++ 11開(kāi)始 const_iterator begin() const noexcept; //從 C++ 11開(kāi)始
沒(méi)有
它返回一個(gè)指向集合的第一個(gè)元素的迭代器。
不變。
沒(méi)有變化。
容器被訪問(wèn)。常量版本和非常量版本都不會(huì)修改容器。
此函數(shù)從不拋出異常。
讓我們看一下begin()函數(shù)的簡(jiǎn)單示例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<string> myset= {"Java", "C++", "SQL"};
// show content:
cout<<"myset的內(nèi)容是: "<<endl;
for (set<string>::iterator it=myset.begin(); it!=myset.end(); ++it)
cout << *it<< '\n';
return 0;
}輸出:
myset的內(nèi)容是: C++ Java SQL
在上面的示例中,begin()函數(shù)用于返回指向myset集合中第一個(gè)元素的迭代器。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#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(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(); // 把它賦給集合的開(kāi)始
while (it != myset.end()) // 雖然還沒(méi)有結(jié)束
{
cout << *it << "\n";
// 打印它指向的元素的值
++it; // 并迭代到下一個(gè)元素
}
cout << endl;
}輸出:
myset的元素是: Aman Deep Nikita Priya Suman
在上面的代碼中,begin()函數(shù)用于返回指向myset集合中第一個(gè)元素的迭代器。
讓我們看一個(gè)簡(jiǎn)單的實(shí)例:
#include <set>
#include <iostream>
int main( )
{
using namespace std;
set <int> s1;
set <int>::iterator s1_Iter;
s1.insert( 1 );
s1.insert( 2 );
s1.insert( 3 );
s1_Iter = s1.begin( );
cout << "s1的第一個(gè)元素是 " << *s1_Iter << endl;
s1_Iter = s1.begin( );
s1.erase( s1_Iter );
s1_Iter = s1.begin( );
cout << "現(xiàn)在s1的第一個(gè)元素是 " << *s1_Iter << endl;
}輸出:
s1的第一個(gè)元素是 1 現(xiàn)在s1的第一個(gè)元素是 2
在上面的示例中,begin()函數(shù)用于返回指向myset集合中第一個(gè)元素的迭代器。