迭代器是一种对象,他能够用来遍历标准模板库容器中的部分或全部元素
每个迭代器对象代表容器中的确定的地址
他提供一些基本操作符 ++ * != 等
迭代器是个所谓的复杂的指针,具有遍历复杂数据结构的能力 其下层运行机制取决于其所遍历的数据结构
每种容器都定义了一对begin和end函数用于返回迭代器
#include <iostream>
#include <string>
using namespace std;
class String
{
public:
String(const char *p = nullptr)
{
if (p != nullptr)
{
_ptr = new char[strlen(p) + 1];
strcpy(_ptr, p);
}
else {
_ptr = new char[1];
*_ptr = '\0';
}
}
~String()
{
delete[]_ptr;
_ptr = nullptr;
}
String(const String &str)
{
_ptr = new char[strlen(str._ptr) + 1];
strcpy(_ptr, str._ptr);
}
String& operator=(const String &src)
{
if (this == &src) { return *this; }
delete[]_ptr;
_ptr = new char[strlen(src._ptr) + 1];
strcpy(_ptr, src._ptr);
return *this;
}
bool operator<(const String &src)const
{
return strcmp(_ptr, src._ptr) < 0;
}
bool operator >(const String &src)const
{
return strcmp(_ptr, src._ptr) > 0;
}
bool operator ==(const String &src)const
{
return strcmp(_ptr, src._ptr);
}
int length()const { return strlen(_ptr); }
const char* c_str()const { return (_ptr+1); }
char& operator[](int index) { return _ptr[index]; }
const char&operator[](int index)const { return _ptr[index]; }
//给String字符串类型提供迭代器的实现
//迭代器的功能:提供一种统一的方式来透明的遍历容器
class iterator
{
public:
iterator(char *p=nullptr):_p(p){}
bool operator!=(const iterator &src)const
{
return _p != src._p;
}
void operator ++()
{
++_p;
}
char & operator*() { return *_p; }
private:
char *_p;
};
//容器底层首元素的迭代器的表示
iterator begin() { return iterator(_ptr); }
iterator end() { return iterator(_ptr + length()); }
private:
char *_ptr;
friend ostream& operator<<(ostream &out, const String &src);
friend String operator+(const String &lhs, const String &rhs);
};
String operator+(const String &lhs,const String &rhs)
{
char *ptmp = new char[strlen(lhs._ptr) + strlen(rhs._ptr)+1];
strcpy(ptmp, lhs._ptr);
strcat(ptmp, rhs._ptr);
String tmp(ptmp);
delete[]ptmp;
return tmp;
}
ostream& operator<<( ostream &out, const String &src)
{
out << src._ptr<< endl;
return out;
}
int main()
{
string str1 = "hello world!";
//容器的迭代器类型
string::iterator it = str1.begin();
for (; it != str1.end(); ++it)
{
cout << *it << " ";
}
cout << endl;
}
我们使用容器的迭代器对容器进行遍历
在vector模板类下实例化一个int型的vector容器
vector<int>str;
定义容器的迭代器
vector<int>::iterator it = str.begin();
//把容器中的所有偶数全部删除
for (; it != str.end(); ++it)
{
if (*it % 2 == 0)
{
str.erase(it);//用来删除迭代器所在未知的元素
//break;
}
}
//在每一个偶数前插入小于1的数
for (; it != str.end(); ++it)
{
if (*it % 2 == 0)
{
str.insert(it, *it - 1);//用来在it所在位置插入元素
//break;
}
}
当容器调用erase方法后,迭代器当前位置到容器末尾元素的所有迭代器全部失效了
当容器调用insert方法后,当前位置到容器末尾元素的所有迭代器全部失效
insert来说,如果引起容器内存扩容,容器要重新开辟新的空间,内存会改变则原来容器的所有迭代器会全部失效
不同容器的迭代器不能进行比较运算
怎么解决迭代器失效问题?
对删除/插入点的迭代器进行更新操作
while (it != str.end())
{
if (*it % 2 == 0)
{
it=str.erase(it);//用来删除迭代器所在未知的元素
//break;
}
else
{
++it;
}
}
for (; it != str.end(); ++it)
{
if (*it % 2 == 0)
{
it=str.insert(it, *it - 1);//用来在it所在位置插入元素
//break;
++it;
}
}
如果需要知道当前迭代器迭代的是哪个容器对象,可以给迭代器添加变量
vector<T,Alloc> *_pvec;//容器名 指针