C++ unordered_set::cbegin() 函式



C++ std::unordered_set::cbegin() 函式用於返回指向無序集合容器中第一個元素的 const_iterator。如果無序集合為空,則返回的 const_iterator 將等於 end()。

const_iterator 是一種迭代器,它指向元素上的 const 值(如指標),並提供對每個單獨元素的訪問。const_iterator 不允許修改無序集合容器中可用的指向元素。

語法

以下是 std::unordered_set::cbegin() 函式的語法。

const_iterator cbegin() const noexcept;
or
const_local_iterator cbegin ( size_type n ) const;

引數

  • n - 它表示桶號,必須小於 bucket_count。

返回值

此函式返回一個指向無序集合容器中第一個元素的 const 迭代器。

示例 1

讓我們看下面的例子,我們將演示 unordered_set::cbegin() 函式的使用。

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;

int main () {
   std::unordered_set<std::string> myUset =
      {"100","200","300","400","500","600","700","800"};
   cout<<"Contents of the myUset are: "<<endl;
   for(auto it: myUset)
      cout<<it<<" ";
   cout<<"\nAn iterator of the first is: ";
      auto it = myUset.cbegin();
      cout<<*it;
   return 0;
}

輸出

讓我們編譯並執行以上程式,這將產生以下結果:

Contents of the myUset are: 
700 600 500 800 400 300 200 100 
An iterator of the first is: 700

示例 2

考慮以下示例,我們將使用 cbegin() 函式內部的迴圈來顯示容器中一定範圍內的元素。

#include <iostream>
#include <string>
#include <unordered_set>

int main () {
   std::unordered_set<std::string> myUset =
      {"100","200","300","400","500"};
      
   std::cout << "myUset contains:";
   for ( auto it = myUset.cbegin(); it != myUset.cend(); ++it )
      std::cout << " " << *it;
   std::cout << std::endl;
   
   return 0;
}

輸出

如果我們執行以上程式碼,它將生成以下輸出:

myUset contains: 500 400 300 200 100

示例 3

在下面的示例中,我們將使用接受 i 作為引數的 cbegin() 函式來返回每個桶的元素。

#include <iostream>
#include <string>
#include <unordered_set>

int main () {
   std::unordered_set<std::string> myUset = {"100", "200", "300", "400", "500"};
      
   std::cout << "myUset's buckets contain:\n";
   for ( unsigned i = 0; i < myUset.bucket_count(); ++i) {
      std::cout << "bucket #" << i << " contains:";
      for ( auto local_it = myUset.cbegin(i); local_it!= myUset.cend(i); ++local_it )
         std::cout << " " << *local_it;
      std::cout << std::endl;
   }
   return 0;
}

輸出

以下是以上程式碼的輸出:

myUset's buckets contain:
bucket #0 contains:
bucket #1 contains: 400
bucket #2 contains: 500
bucket #3 contains:
bucket #4 contains: 100
bucket #5 contains:
bucket #6 contains:
bucket #7 contains:
bucket #8 contains:
bucket #9 contains:
bucket #10 contains: 300
bucket #11 contains: 200
bucket #12 contains:

示例 4

以下是示例,我們將使用 cbegin() 函式獲取指向第一個元素的 const 迭代器。

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;

int main () {
   unordered_set<int> myUset = {10, 20, 30, 40, 50};
      
   cout << "Iterator pointing to the first element of the bucket 4 is: ";
   auto it = myUset.cbegin(4);
   cout<<*it<<endl;
   return 0;
}

輸出

以上程式碼的輸出如下:

Iterator pointing to the first element of the bucket 4 is: 30
廣告

© . All rights reserved.