C ++ set begin()函数用于返回引用set容器的第一个元素的迭代器。
语法
iterator begin(); //直到 C ++ 11
const_iterator begin() const; //直到 C ++ 11
iterator begin() noexcept; //从 C++ 11开始
const_iterator begin() const noexcept; //从 C++ 11开始
参数
没有
返回值
它返回一个指向集合的第一个元素的迭代器。
复杂性
不变。
迭代器有效性
没有变化。
数据争用
容器被访问。常量版本和非常量版本都不会修改容器。
异常安全
此函数从不抛出异常。
实例1
让我们看一下begin()函数的简单示例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
set<string> myset= {"Java", "C++", "SQL"};
// show content:
cout<<"myset的内容是: "<<endl;
for (set<string>::iterator it=myset.begin(); it!=myset.end(); ++it)
cout << *it<< '\n';
return 0;
}
输出:
myset的内容是:
C++
Java
SQL
在上面的示例中,begin()函数用于返回指向myset集合中第一个元素的迭代器。
实例2
让我们看一个简单的实例:
#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
实例3
让我们看一个简单的示例,使用while循环遍历集合:
#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; // 声明一个迭代器
it = myset.begin(); // 把它赋给集合的开始
while (it != myset.end()) // 虽然还没有结束
{
cout << *it << "\n";
// 打印它指向的元素的值
++it; // 并迭代到下一个元素
}
cout << endl;
}
输出:
myset的元素是:
Aman
Deep
Nikita
Priya
Suman
在上面的代码中,begin()函数用于返回指向myset集合中第一个元素的迭代器。
实例4
让我们看一个简单的实例:
#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的第一个元素是 " << *s1_Iter << endl;
s1_Iter = s1.begin( );
s1.erase( s1_Iter );
s1_Iter = s1.begin( );
cout << "现在s1的第一个元素是 " << *s1_Iter << endl;
}
输出:
s1的第一个元素是 1
现在s1的第一个元素是 2
在上面的示例中,begin()函数用于返回指向myset集合中第一个元素的迭代器。
C++ set cend() C++ ~set destructor
展开全部