C++ Set 中的 End函数

首页 / C++入门教程 / C++ Set 中的 End函数

C++ set end()函数用于返回迭代器,该迭代器位于集合中最后一个元素。

Note:- 这是一个占位符。此位置没有元素,尝试访问是未定义的行为。

End - 语法

      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

End - 返回值

它返回一个迭代器,该迭代器指向集合的最后一个元素。

End - 例子1

让我们看一下end()函数的简单示例:

#include <iostream>
#include <set>

using namespace std;

int main ()
{
  set<string> myset = {"Java", "C++", "SQL"};

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

  return 0;
}

输出:

C++
Java
SQL

在上面的示例中,end()函数用于返回指向myset集合中最后一个元素旁边的迭代器。

End - 例子2

让我们看一个简单的示例,使用for-each循环遍历集合:

#include <iostream>
#include <set>

using namespace std;

int main()
{
  set<int> c;
  c.insert(5);
  c.insert(2);
  c.insert(4);
  c.insert(1);
  c.insert(0);
  c.insert(0);
  c.insert(9);

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

输出:

0 1 2 4 5 9

End - 例子3

让我们看一个简单的示例,使用while循环遍历集合:

#include <iostream>
#include <set>
#include <string>
int main()
{
    using namespace std;
 
      set<string> myset = { "Nikita","Deep","Priya","Suman","Aman" };

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

    it = myset.begin();//assign it to the start of the set

    while (it != myset.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 myset are: 
Aman
Deep
Nikita
Priya
Suman

在上面的示例中,end()函数用于返回指向myset集合中最后一个元素旁边的迭代器。

End - 例子4

让我们看一个简单的例子:

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


using namespace std;

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

    auto result = c.find(val);  
    
    //find until end of the set 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: 30
Element found: 30

在上面的示例中,end()函数用于返回指向myset集合中最后一个元素旁边的迭代器。

祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)

技术教程推荐

微服务架构核心20讲 -〔杨波〕

快速上手Kotlin开发 -〔张涛〕

Linux实战技能100讲 -〔尹会生〕

分布式系统案例课 -〔杨波〕

成为AI产品经理 -〔刘海丰〕

网络排查案例课 -〔杨胜辉〕

说透元宇宙 -〔方军〕

B端产品经理入门课 -〔董小圣〕

零基础GPT应用入门课 -〔林健(键盘)〕

好记忆不如烂笔头。留下您的足迹吧 :)