C++ STL 中的 multiset begin() 和 end() 函式


在本文中,我們將討論 C++ STL 中 multiset::begin() 和 multiset::end() 函式的工作原理、語法和示例。

什麼是 C++ STL 中的 multiset?

Multiset 與 set 容器類似,這意味著它們像 set 一樣以鍵的形式儲存值,並按照特定順序排列。

在 multiset 中,值與 set 一樣被標識為鍵。multiset 和 set 之間的主要區別在於,set 的鍵是唯一的,這意味著沒有兩個鍵相同,而在 multiset 中可以存在相同的鍵值。

Multiset 鍵用於實現二叉搜尋樹。

什麼是 multiset::begin()?

multiset::begin() 函式是 C++ STL 中的內建函式,它在 <set> 標頭檔案中定義。

此函式返回一個迭代器,該迭代器指向 multiset 容器中的第一個元素。

由於 multiset 容器按升序儲存值,因此 begin() 指向根據排序標準確定的容器的第一個元素。

語法

ms_name.begin();

引數

此函式不接受任何引數。

返回值

此函式返回一個迭代器,該迭代器指向與其關聯的 multiset 容器的第一個元素。

示例

Input: std::multiset<int> mymultiset = {1, 2, 2, 3, 4};
   mymultiset.begin();
Output: 1

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   int arr[] = {2, 4, 1, 3, 8, 5, 6};
   multiset<int> check(arr, arr + 7);
   cout<<"List is : ";
   for (auto i = check.begin(); i != check.end(); i++)
      cout << *i << " ";
   cout<<"\nStarting Element is : "<<*(check.begin());
   return 0;
}

輸出

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

List is : 1 2 3 4 5 6 8
Starting Element is : 1

什麼是 multiset::end()

multiset::end() 函式是 C++ STL 中的內建函式,它在 <set> 標頭檔案中定義。

此函式返回一個迭代器,該迭代器指向 multiset 容器中末尾之後的那個位置。

末尾之後的元素是指 multiset 容器最後一個元素之後的元素。簡而言之,它不指向 multiset 容器中的任何特定元素。此函式通常與 begin() 一起使用以給出 multiset 容器的範圍。

語法

ms_name.end();

引數

此函式不接受任何引數。

返回值

此函式返回一個迭代器,該迭代器指向與其關聯的 multiset 容器的末尾元素之後的位置。

示例

Input: std::multiset<int> mymultiset = {1, 2, 2, 3, 4};
   for( std::multiset<int>::iterator it=mymultiset.begin(); it!=mymultiset.end(); ++it )
Output: 1 2 2 3 4

示例

 線上演示

#include <bits/stdc++.h>
using namespace std;
int main() {
   int arr[] = {2, 4, 1, 3, 8, 5, 6};
   multiset<int> check(arr, arr + 7);
   cout<<"List is : ";
   for (auto i = check.begin(); i != check.end(); i++)
      cout << *i << " ";
   return 0;
}

輸出

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

List is : 1 2 3 4 5 6 8

更新於:2020年3月23日

2K+ 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告