C++ Set 中的 cbegin函数

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

C++ set cbegin()函数用于返回指向set集合的第一个元素的常量迭代器。

cbegin - 语法

const_iterator cbegin() const noexcept;  //since C++ 11

const_iterator 是指向常量内容的迭代器。

cbegin - 返回值

它返回一个const_iterator指向集合的第一个元素。

链接:https://www.learnfk.comhttps://www.learnfk.com/c++/cpp-set-cbegin-function.html

来源:LearnFk无涯教程网

cbegin - 例子1

让我们看一下cbegin()函数的简单示例:

#include <iostream>
#include <set>

using namespace std;

int main ()
{
  set<string> myset= {"Java", "C++","SQL"};

 //show content:
  for (auto it = myset.cbegin(); it != myset.cend(); ++it)
    cout <<*it << '\n';
    
  return 0;
}

输出:

C++
Java
SQL

在上面的示例中,cbegin()函数用于返回指向myset集合中第一个元素的常量迭代器。

cbegin - 例子2

让我们看一个简单的例子:

#include <set>  
#include <iostream>  
  
int main( )  
{  
   using namespace std;  
   set <int> s1;  
   set <int>::iterator s1_Iter;  
   set <int>::const_iterator s1_cIter;  
  
   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 );  
  
  //The following 2 lines would err because the iterator is const  
  //s1_cIter = s1.begin( );  
  //s1.erase( s1_cIter );  
  
   s1_cIter = s1.begin( );  
   cout << "The first element of s1 is now " << *s1_cIter << endl;  
}  

输出:

The first element of s1 is 1
The first element of s1 is now 2

cbegin - 例子3

让我们看一个简单的示例,使用while循环遍历集合:

#include <iostream>
#include <set>
#include <string>
int main()
{
    using namespace std;
 
      set<string> myset = {"Robin","Dolly", "John","Nikita"};

    set<string>::const_iterator it;//declare an iterator

    it = myset.cbegin();//assign it to the start of the vector

    while (it != myset.cend())//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;
}

输出:

Dolly
John
Nikita
Robin

在上面的示例中,cbegin()函数用于返回指向myset集合中第一个元素的迭代器。

cbegin - 例子4

让我们看另一个简单的例子:

无涯教程网

#include <iostream>
#include <string>
#include <set>

using namespace std;

int main ()
{
  set<int> number = {400, 350, 465, 290, 410};

   cout << "Increasing order: " << '\n';
   cout<<"______________________\n";
   
  set<int>::const_iterator cit;
  for (cit=number.cbegin(); cit!=number.cend(); ++cit)
    cout << *cit<< '\n';

    auto low = number.cbegin();
    auto high = number.rbegin();
    
    cout << "\nSmallest Number is: "<< *low <<endl;
    cout<< "Biggest Number is: "<<*high <<endl;

  return 0;
  }  

输出:

Increasing order: 
______________________
290
350
400
410
465
Smallest Number is: 290
Biggest Number is: 465

在上面的示例中,cbegin()函数用于返回指向myset集合中第一个元素的迭代器。

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

技术教程推荐

OpenResty从入门到实战 -〔温铭〕

Kafka核心技术与实战 -〔胡夕〕

深入浅出云计算 -〔何恺铎〕

说透数字化转型 -〔付晓岩〕

Go 语言项目开发实战 -〔孔令飞〕

网络排查案例课 -〔杨胜辉〕

超级访谈:对话汤峥嵘 -〔汤峥嵘〕

林外 · 专利写作第一课 -〔林外〕

后端工程师的高阶面经 -〔邓明〕

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