c++ vector v.rend()举例
时间: 2024-01-10 22:21:28 浏览: 30
引用[1]和引用[2]提供了两个关于C++中vector的示例代码。下面是关于C++ vector的rend()函数的介绍和示例:
rend()函数是vector容器的一个成员函数,它返回一个反向迭代器,指向容器的最后一个元素的下一个位置。也就是说,rend()函数返回的迭代器指向的是容器中最后一个元素之后的位置。
下面是一个使用rend()函数的示例代码:
```cpp
#include <iostream>
#include <vector>
using namespace std;
int main() {
vector<int> v;
for (int i = 1; i <= 5; i++) {
v.push_back(i);
}
// 使用rend()函数遍历vector容器
for (vector<int>::reverse_iterator rit = v.rbegin(); rit != v.rend(); ++rit) {
cout << *rit << " "; }
cout << endl;
return 0;
}
```
输出结果为:
5 4 3 2 1
在上面的示例中,我们首先创建了一个包含1到5的整数的vector容器。然后,使用reverse_iterator从容器的最后一个元素开始遍历到第一个元素,并输出每个元素的值。
相关问题
error: need ‘typename’ before ‘T:: iterator’ because ‘T’ is a dependent scope for(T::iterator it = v.begin();it != v.rend();++it) ^ vfun.cpp:16:18: error: expected ‘;’ before ‘it’ for(T::iterator it = v.begin();it != v.rend();++it) ^~ vfun.cpp:16:33: error: ‘it’ was not declared in this scope for(T::iterator it = v.begin();it != v.rend();++it) ^~ vfun.cpp:16:33: note: suggested alternative: ‘int’ for(T::iterator it = v.begin();it != v.rend();++it) ^~ int vfun.cpp: In instantiation of ‘void show(T) [with T = std::vector<int>]’: vfun.cpp:23:9: required from here vfun.cpp:16:32: error: dependent-name ‘T:: iterator’ is parsed as a non-type, but instantiation yields a type for(T::iterator it = v.begin();it != v.rend();++it)
这个错误是因为在模板函数内部使用了依赖名称,编译器无法确定 T::iterator 是类型还是成员变量,需要使用 typename 来明确告诉编译器 T::iterator 是一个类型,例如:
```
for(typename T::iterator it = v.begin(); it != v.end(); ++it)
```
在迭代器前加上 typename 关键字即可。
vector<int>(res.rbegin(), res.rend())
这是一个将vector容器中元素反转的方法。
其中,`rbegin()`返回一个指向vector容器末尾的反向迭代器,`rend()`返回一个指向vector容器起始位置前一个元素的反向迭代器。
在这里,`vector<int>(res.rbegin(), res.rend())`使用了vector的构造函数,将迭代器从末尾到起始位置的元素复制到一个新的vector中,并返回这个新的vector,达到反转vector的目的。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![h](https://img-home.csdnimg.cn/images/20210720083646.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)