C++ string类迭代器begin/end与rbegin/rend的使用

C++ string类迭代器begin/end与rbegin/rend的使用

🔥迭代器接口(iterators)

什么是迭代器接口,就是成员函数返回迭代器的接口,也就是获取迭代器的方法。我们可以先将迭代器想象成指向容器元素的指针,而这些成员函数的作用就是让我们获取这些指针。同时我们可以通过+,-,++或--等运算符调整这种指针的指向。

==begin==

iterator begin();const_iterator begin() const;这两个成员函数都返回一个指向string串中第一个元素的正向迭代器。

==end==

iterator end();const_iterator end() const;这两个成员函数都返回一个指向string串中最后一个元素下一位的正向迭代器。

使用样例:

// string::begin/end

#include

#include

using namespace std;

int main()

{

std::string str("Test string");

string::iterator it = str.begin();

for (; it != str.end(); ++it)

cout << *it;

cout << endl;

return 0;

}

string的迭代器(iterator)是一个定义在string类内部的一个类型,它能指向string对象的元素,而迭代器的对象可以通过string提供的成员函数获取。上述代码案例中的迭代器it被我们称为正向迭代器,++使其向后移动指向下一元素,--使其向前移动指向上一元素。而接下来我们要讲的rbegin和rend,是获取反向迭代器的两个接口函数。

==rbegin==

reverse_iterator rbegin();const_reverse_iterator rbegin() const;这两个成员函数都返回一个指向string串中最后一个元素的反向迭代器。

==rend==

reverse_iterator rend();const_reverse_iterator rend() const;

这两个成员函数都返回一个指向string串中第一个元素上一位的反向迭代器。使用样例:

// string::rbegin/rend

#include

#include

using namespace std;

int main()

{

string str("now step live...");

string::reverse_iterator rit = str.rbegin();

for (; rit != str.rend(); ++rit)

cout << *rit;

cout << endl;

return 0;

}

同理,string的反向迭代器(reverse_iterator)是一个定义在string类内部的一个类型,它能指向string对象的元素,而反向迭代器的对象可以通过string提供的成员函数获取。反向迭代器,++使其向前移动指向上一元素,--使其后前移动指向下一元素。

==cbgin,cend,erbegin和crend==

这几个作为C++11新增语法,专门提供了获取const类型的四种迭代器接口,使迭代器可以读,但不能通过迭代器解引用更改串中的内容。这里就不多做赘述。

结语

本篇博客讲了关于string类构造的七种重载,赋值运算符的三种重载,以及各种string迭代器接口的使用。后面博主会继续分享关于string类的使用以及STL更多的内容,感谢大家的支持。♥

相关推荐

河南总共有多少个县
beat365网站老板

河南总共有多少个县

🕒 10-17 👁️ 9387
深圳阳刚同志桑拿
beat365网站老板

深圳阳刚同志桑拿

🕒 09-02 👁️ 980