當前位置: 首頁>>編程示例 >>用法及示例精選 >>正文


C++ multiset end()用法及代碼示例

C++ multiset end() 函數用於返回一個迭代器,它位於 multiset 中最後一個條目的旁邊。

注意:- 這是一個占位符。此位置不存在元素,嘗試訪問是未定義的行為。

用法

iterator end();                            //until C++ 11

const_iterator end() const;                //until C++ 11

      iterator end() noexcept;              //since C++ 11

const_iterator end() const noexcept;  //since C++ 11

參數

返回值

它返回一個指向多重集最後一個元素旁邊的迭代器。

複雜度

恒定。

迭代器有效性

沒有變化。

數據競爭

同時訪問多重集的元素是安全的。

容器不會被訪問,非常量和常量版本都不會修改容器。

異常安全

此成員函數從不拋出異常。

例子1

讓我們看看 end() 函數的簡單示例:

#include <iostream>
#include <set>

using namespace std;

int main ()
{
  multiset<string> mymultiset = {"Java", "C++", "Java", "C++"};

  // show content:
  for (multiset<string>::iterator it=mymultiset.begin(); it!=mymultiset.end(); ++it)
    cout << *it<< '\n';

  return 0;
}

輸出:

C++
C++
Java
Java

在上麵的示例中,end() 函數用於返回指向 mymultiset 多集中最後一個元素旁邊的迭代器。

例子2

讓我們看一個使用 for-each 循環迭代多重集的簡單示例:

#include <iostream>
#include <set>

using namespace std;

int main()
{
  multiset<int> c;
  c.insert(5);
  c.insert(2);
  c.insert(1);
  c.insert(1);
  c.insert(0);
  c.insert(0);
  c.insert(2);

  multiset<int>::iterator i = c.begin();
  while (i != c.end())
    cout << *i++ << " ";
  cout << endl;
}

輸出:

0 0 1 1 2 2 5

例子3

讓我們看一個使用 while 循環遍曆多重集的簡單示例:

#include <iostream>
#include <set>
#include <string>

int main()
{
    using namespace std;
 
      multiset<string> mymultiset = { "Nikita","Deep","Deep","Sonu","Aman" };

 cout<<"Elements of mymultiset are:"<<endl;
    multiset<string>::const_iterator it; // declare an iterator

    it = mymultiset.begin(); // assign it to the start of the multiset

    while (it != mymultiset.end()) // while it hasn't reach the end
    {
cout << *it << "\n"; 

// print the value of the element it points to

++it; // and iterate to the next element
    }
 
    cout << endl;
}

輸出:

Elements of mymultiset are:
Aman
Deep
Deep
Nikita
Sonu

在上麵的示例中,end() 函數用於返回指向 mymultiset 多集中最後一個元素旁邊的迭代器。

示例 4

讓我們看一個簡單的例子:

#include <iostream>
#include <string>
#include <set>


using namespace std;

int main ()
{
    int val;
    multiset<int> c = {10,20,10,20,40,50};
 
    cout<<"Enter value to find:";
    cin>>val;

    auto result = c.find(val);  
    
    //find until end of the multiset elements
    if (result != c.end()) {  
        cout << "Element found:"<< *result; 
        cout << endl;  
    } else {  
        cout << "Element not found." << endl;  
    }  
    
  return 0;
}

輸出:

Enter value to find:60
Element not found.


Enter value to find:20
Element found:20

在上麵的示例中,end() 函數用於返回指向 mymultiset 多集中最後一個元素旁邊的迭代器。





相關用法


注:本文由純淨天空篩選整理自 C++ multiset end()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。