C++ Unordered_set::cend() 函式



C++ std::unordered_set::cend() 函式用於返回一個 const_iterator,指向無序集合容器中最後一個元素的下一個位置。cend() 返回的 const_iterator 不指向任何元素,而是指向無序集合容器中最後一個元素之後的那個位置。

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

unordered_set::cend() 函式類似於 unordered_set::end() 函式。cend() 函式只返回一個 const_iterator,而 end() 函式只返回一個 iterator。

語法

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

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

引數

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

返回值

此函式返回一個 const_iterator,指向無序集合容器中最後一個元素之後的那個位置。

示例 1

讓我們看下面的例子,我們將使用迴圈來顯示容器中一定範圍內的元素。

#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

示例 2

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

#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:

示例 3

在下面的例子中,我們將使用 cend() 函式透過使用 while 迴圈迭代無序集合來獲取無序集合容器的元素。

#include <iostream>
#include <unordered_set>  
#include <string> 
using namespace std;
 
int main() {
   unordered_set<int> myset = { 10,20,30,40,50 };  
      cout<<"Elements of myUset are: "<<endl;  
   unordered_set<int>::const_iterator it; // declare an iterator 
   it = myset.begin();
   while (it != myset.cend()) {  
      cout << *it << "\n"; 
      ++it; // iterate to the next element  
   }  
   cout << endl;  
   return 0;
} 

輸出

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

Elements of myUset are: 
50
40
30
20
10
廣告
© . All rights reserved.