一:通用算法
在迭代器的基础的通用算法:
- insert 插入
- erase 删除
- find 查找(不适用于适配器容器)
(一):find查找
find函数返回的是一个迭代器
注意:当没有查找到时,返回的是迭代器的最后位置(end)而不是nullptr。
#include<iostream>
#include<algorithm>
#include<string>
#include<list>
using namespace std;
int main()
{
//find:查找
vector<string> myString(4);
myString[0] = "tust";
myString[1] = "tianjin";
myString[2] = "artificial";
myString[0] = "intelligence";
//find返回的是一个迭代器
cout << *find(myString.begin(), myString.end(), "artificial") << endl;
//没有找到,引起中断
//cout << *find(myString.begin(), myString.end(), "college") << endl;
//查找算法唯一要处理没有找到的情况
vector<string>::iterator iter = find(myString.begin(), myString.end(), "college");
if (iter == myString.end())//未找到的情况下find返回的是迭代器最后的位置
{
cout << "没有找到college" << endl;
}
list<int> myList;
myList.push_front(1);
myList.push_back(2);
myList.push_back(3);
list<int>::iterator listIter = find(myList.begin(), myList.end(), 1);
cout << *listIter << endl;
system("pause");
return 0;
}
(二):insert 插入
insert常结合find一起使用。在指定位置前面进行插入(若要在指定位置后面进行插入则需要对迭代器进行前置++操作)
#include<iostream>
#include<algorithm>
#include<functional>
#include<string>
#include<vector>
#include<list>
using namespace std;
template<typename T>
void print(T data)
{
cout << data << " ";
}
int main()
{
list<int> myList;
myList.push_front(1);
myList.push_back(2);
myList.push_back(3);
list<int>::iterator listIter = find(myList.begin(), myList.end(), 1);
cout << *listIter << endl;
//insert:插入(结合find算法)(指定位置前面查找,若要在指定位置后面查找则需要对迭代器进行前置++操作)
cout << "插入前:" << endl;
for_each(myList.begin(), myList.end(), print<int>);
cout << "在迭代器前面进行插入操作" << endl;
myList.insert(listIter, 0); //在迭代器listIter前面进行插入,插入0
for_each(myList.begin(), myList.end(), print<int>);
cout << "在迭代器后面进行插入操作" << endl;
myList.insert(++listIter, 3); //在迭代器listIter后面进行插入,插入3 前置++, 这里不能用后置++和listIter+1(迭代器内部没有重载+,而是重载了++)
for_each(myList.begin(), myList.end(), print<int>);
cout << endl;
system("pause");
return 0;
}
(三):erase删除
- 删除一段元素(clear():删除所有元素)
//1.删一段元素
//删除所有元素: clear();
myString.erase(myString.begin(), myString.end()); //删除容器中一段元素
- 删除指定位置元素
//删除指定元素
//从前往后查找3,并将其删除
myList.erase(find(myList.begin(),myList.end(),3)); //若有多个重复的数字在列表中,find返回靠前的数字对应的迭代器
for_each(myList.begin(), myList.end(), print<int>);
cout << endl;