C++ List::crend() 函数



C++ 的 std::list::crend() 函数用于获取一个指向反转列表的最后一个元素之后元素的常量反向迭代器。

const_reverse_iterator 是一种迭代器,它向后迭代,同时指向一个常量迭代器。const_reverse_iterator 值确定它在列表容器中的起始位置和结束位置。但是,即使列表元素不是常量,它也不能用于修改它指向的内容。

语法

以下是 C++ std::list::crend() 函数的语法:

const_reverse_iterator crend() const;

参数

  • 它不接受任何参数。

返回值

此函数返回一个指向反转列表的最后一个元素之后元素的常量反向迭代器。

示例 1

在下面的程序中,我们使用 C++ std::list::crend() 函数来获取一个指向当前列表 {10, 20, 30, 40} 的最后一个元素之后元素的常量迭代器。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<int> num_list = {10, 20, 30, 40};
   cout<<"List elements are: ";
   for(int n : num_list) {
      cout<<n<<" ";
   }
   auto it = num_list.crend();
   cout<<"\nA constant reverse iterator of the last element: ";
   cout<<*it;
}

输出

以下是上述程序的输出:

List elements are: 10 20 30 40 
A constant reverse iterator of the last element: 4

示例 2

除了 int 类型的列表元素外,您还可以检索任何其他类型的列表元素(如 char 和 string 列表内容)的迭代器。

以下是 C++ std::list::crend() 函数的另一个示例。这里,我们创建了一个名为 char_list 的列表(类型为 char),其值为 {'a', 'b', 'c', 'd', 'e', 'f'}。然后使用 crend() 函数,我们试图检索一个指向反转列表的最后一个元素之后的常量反向迭代器。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<char> char_list = {'a', 'b', 'c', 'd', 'e', 'f'};
   cout<<"List elements are: ";
   for(char v : char_list) {
      cout<<v<<" ";
   }
   auto it = char_list.crend();
   cout<<"\nA constant reverse iterator of the last element: ";
   cout<<*it;
}

输出

这将生成以下输出:

List elements are: a b c d e f 
A constant reverse iterator of the last element: 

示例 3

如果列表类型是字符串。

在此示例中,我们创建了一个名为 str_list 的列表(类型为 string),其值为 {"Java", "HTML", "CSS", "Angular"}。然后,使用 crend() 函数,我们试图检索一个指向反转列表的最后一个元素之后的常量反向迭代器。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<string> str_list  =  {"Java", "HTML", "CSS", "Angular"};
   cout<<"List elements are: ";
   for(string s : str_list ) {
      cout<<s<<" ";
   }
   auto it = str_list.crend();
   cout<<"\nA constant reverse iterator of the last element: ";
   cout<<*it;
}

输出

上述程序产生以下输出:

List elements are: Java HTML CSS Angular 
A constant reverse iterator of the last element:
Segmentation fault

示例 4

使用 for 循环以及 crend() 函数来检索反转列表的常量反向迭代器。

在此示例中,我们使用 crend() 函数以及 for 循环遍历当前容器 {1, 2, 3, 4 ,5, 6, 7, 8, 9, 10} 并检索反转列表所有元素的常量反向迭代器。

#include<iostream>
#include<list>
using namespace std;

int main() {
   //create a list
   list<int> num_list = {1, 2, 3, 4 ,5, 6, 7, 8, 9, 10} ;
   cout<<"List elements are: ";
   for(int n : num_list) {
      cout<<n<<" ";
   }
   cout<<"\nThe constant reverse iterator of an elements are : ";
   for (auto it = num_list.crbegin(); it != num_list.crend(); it++) {
      cout<<*it<<" ";
   }
}

输出

执行上述程序后,它将产生以下输出:

List elements are: 1 2 3 4 5 6 7 8 9 10 
The constant reverse iterator of an elements are : 10 9 8 7 6 5 4 3 2 1 
广告