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
广告