C++ unordered_set::begin() 函式



C++ std::unordered_set::begin() 函式用於返回指向 unordered_set 容器第一個元素的迭代器。如果 unordered_set 為空,則返回的迭代器將等於 end()。

迭代器是遍歷元素的物件(類似於指標),它提供對每個單個元素的訪問。迭代器可用於修改 unordered_set 容器中可用的指向元素。

語法

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

iterator begin() noexcept;
const_iterator begin() const noexcept;
or
local_iterator begin ( size_type n );
const_local_iterator begin ( size_type n ) const;

引數

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

返回值

此函式返回指向 unordered_set 容器中第一個元素的迭代器,或者指向指定桶中第一個元素的迭代器。

示例 1

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

#include <iostream>
#include <string>
#include <unordered_set>
using namespace std;
int main () {
   unordered_set<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.begin();
      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

考慮下面的例子,我們將使用 begin() 函式在 for 迴圈內顯示容器的元素。

#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.begin(); it != myUset.end(); ++it )
      std::cout << " " << *it;
   std::cout << std::endl;
   
   return 0;
}

輸出

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

myUset contains: 500 400 300 200 100

示例 3

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

#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.begin(i); local_it!= myUset.end(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

以下是 begin() 函式的另一個用法示例,用於獲取指向指定桶的第一個元素的迭代器。

#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.begin(4);
   cout<<*it<<endl;
   return 0;
}

輸出

上述程式碼的輸出如下:

Iterator pointing to the first element of the bucket 4 is: 30
廣告
© . All rights reserved.