C++教程
C++控制语句
C++函数
C++数组
C++指针
C++对象
C++继承
C++多态
C++抽象
C++常用
C++ STL教程
C++迭代器
C++程序

C++ Set begin()

C++ Set begin()

C++ Set begin()函数用于返回引用set容器第一个元素的迭代器。

语法

      iterator begin();                            //until C++ 11
const_iterator begin() const;                //until C++ 11
      iterator begin() noexcept;              //since C++ 11
const_iterator begin() const noexcept;  //since C++ 11

参数

返回值

它返回指向迭代器第一个元素的迭代器 Set 。

复杂度

常量。

迭代器有效性

没有变化。

数据争用

已访问容器。

异常安全

此函数从不抛出异常。

示例1

让我们看一下begin()函数的简单示例:
#include <iostream>
#include <set>
using namespace std;
int main ()
{
  set<string> myset= {"Java", "C++", "SQL"};
  // show content:
  cout<<"Contents of myset are: "<<endl;
  for (set<string>::iterator it=myset.begin(); it!=myset.end(); ++it)
    cout << *it<< '\n';
  return 0;
}
输出:
Contents of myset are: 
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<<"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
在上面,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 << "The first element of s1 is " << *s1_Iter << endl;  
  
   s1_Iter = s1.begin( );  
   s1.erase( s1_Iter );  
   s1_Iter = s1.begin( );  
   cout << "The first element of s1 is now " << *s1_Iter << endl;  
}
输出:
The first element of s1 is 1
The first element of s1 is now 2
在上面的示例中,begin()函数用于返回指向myset集中第一个元素的迭代器。

昵称: 邮箱:
Copyright © 2022 立地货 All Rights Reserved.
备案号:京ICP备14037608号-4