C++ STL 中的 list end() 函数
在本文中,我们将讨论 C++ 中 list::end() 函数的工作原理、语法和示例。
什么是 STL 中的 List?
List 是一种数据结构,允许在序列中的任何位置进行常数时间插入和删除操作。列表实现为双向链表。列表允许非连续内存分配。与数组、向量和双端队列相比,列表在容器中的任何位置执行元素的插入、提取和移动操作的效率更高。在列表中,直接访问元素的速度较慢,并且列表类似于 forward_list,但 forward_list 对象是单向链表,只能向前迭代。
什么是 list::end()?
list::end() 是 C++ STL 中一个内置函数,声明在 <list> 头文件中。end() 返回一个迭代器,该迭代器指向列表容器中末尾位置的下一个元素。此函数不指向容器中的任何元素。
此函数通常与 list::begin() 一起使用,以给出特定列表容器的范围。
语法
list_container.end();
此函数不接受任何参数。
返回值
此函数返回指向列表容器末尾元素之后的迭代器。
示例
/* 下面的代码使用 end() 函数遍历列表中存在的元素。 */
#include <bits/stdc++.h>
using namespace std;
int main(){
//create a list
list<int> myList;
//insert elements to List suing push_back() function
myList.push_back(67);
myList.push_back(12);
myList.push_back(32);
myList.push_back(780);
myList.push_back(78);
cout<<"elements in the list are :\n";
for (auto j = myList.begin(); j!= myList.end(); j++){
cout << *j << " ";
}
return 0;
}示例
如果我们运行上面的代码,它将生成以下输出
Elements in the list are: 67 12 32 780 78
示例
/* 下面的代码使用头文件来访问使用 end() 函数存在的列表中的元素。 */
#include <iostream>
#include <list>
int main (){
//creating array of elements
int values[] = {67, 12, 32, 780, 78};
//inserting values to the list
std::list<int> myList (values,values+5);
std::cout << "elements in the list are :\n";
//accessing list elements using iterator returned by an end() function
for (std::list<int>::iterator i = myList.begin() ; i != myList.end(); ++i)
std::cout << ' ' << *i;
return 0;
}输出
如果我们运行上面的代码,它将生成以下输出
Elements in the list are: 67 12 32 780 78
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP