當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ multiset cbegin()用法及代碼示例

C++ multiset cbegin() 函數用於返回一個常量迭代器,指向 multiset 容器的第一個元素。

用法

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

const_iterator 是一個指向常量內容的迭代器。

參數

返回值

cbegin() 函數返回一個 const_iterator 指向多重集的第一個元素。

複雜度

持續的

迭代器有效性

沒有變化。

數據競爭

容器被訪問。

同時訪問多集容器的元素是安全的。

異常安全

此成員函數從不拋出異常。

例子1

讓我們看看 cbegin() 函數的簡單示例:

#include <iostream>
#include <set>

using namespace std;

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

  // show content

  for (auto it = mymultiset.cbegin(); it != mymultiset.cend(); ++it)
    cout <<*it << '\n';
    
  return 0;
}

輸出:

C
C++
Java
SQL

在上麵的例子中,cbegin() 函數用於返回一個指向 mymultiset 多重集中第一個元素的常量迭代器。

例子2

讓我們看一個簡單的例子:

#include <set>  
#include <iostream>  
  
int main( )  
{  
   using namespace std;  
   multiset <int> s1;  
   multiset <int>::iterator s1_Iter;  
   multiset <int>::const_iterator s1_cIter;  
  
   s1.insert( 1 );  
   s1.insert( 2 );  
   s1.insert( 3 );  
   s1.insert( 2 );
   
   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

例子3

讓我們看一個使用 while 循環遍曆多重集的簡單示例:

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

int main()
{
    using namespace std;
 
      multiset<string> mymultiset = {"Robin","Dolly", "John","Nikita","Nikita"};

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

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

    while (it != mymultiset.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
Nikita
Robin

在上麵的例子中, cbegin() 函數用於返回一個指向 mymultiset 多集中第一個元素的迭代器。

示例 4

讓我們看另一個簡單的例子:

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

using namespace std;

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

   cout << "Increasing order:" << '\n';
   cout<<"______________________\n";
   
  multiset<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
400
410
465

Smallest Number is:290
Biggest Number is:465

在上麵的例子中, cbegin() 函數用於返回一個指向 mymultiset 多集中第一個元素的迭代器。





相關用法


注:本文由純淨天空篩選整理自 C++ multiset cbegin()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。