C++ Set 中的 Begin函数

首页 / C++入门教程 / C++ Set 中的 Begin函数

C++ set Begin()函数用于返回引用set集合的第一个元素的迭代器。

Begin - 语法

      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

Begin - 返回值

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

Begin - 例子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集合中第一个元素的迭代器。

无涯教程网

Begin - 例子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

Begin - 例子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集合中第一个元素的迭代器。

Begin - 例子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集合中第一个元素的迭代器。

无涯教程网

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

算法面试通关40讲 -〔覃超〕

数据分析实战45讲 -〔陈旸〕

Java性能调优实战 -〔刘超〕

说透敏捷 -〔宋宁〕

分布式协议与算法实战 -〔韩健〕

Serverless入门课 -〔蒲松洋(秦粤)〕

超级访谈:对话玉伯 -〔玉伯〕

结构学习力 -〔李忠秋〕

结构思考力 · 透过结构看表达 -〔李忠秋〕

好记忆不如烂笔头。留下您的足迹吧 :)