海绵宝宝撒
我写的模板函数接受3个参数,前两个参数定义要搜索的区间,第三个参数决定连续多少个相同的元素,返回值是找到的第一个连续4个相同元素的起始位置和终止位置的迭代器,这两个迭代器组成一个pair对象。(根据stl惯例,这两个迭代器定义的区间是左闭右开的)把这两个迭代器送给erase函数做参数,就可以删除想删除的元素。示例如下:===================================================#include <iostream>using std::cout;using std::endl;#include <vector>using std::vector;using std::pair;template <typename InputIterator>std::pair<InputIterator, InputIterator>find_equal_sequence(InputIterator first, InputIterator last, int n) {if (first != last) {InputIterator cur(first), start(cur++);for (int c = 1; cur != last; ++cur) {if (*cur == *start) {if (++c == n)return std::make_pair(start, ++cur);} else {start = cur;c = 1;}}}return std::make_pair(last, last);}int main() {int array[] = { 1, 2, 1, 2, 3, 3, 3, 3, 4, 4, };vector<int> v(array, array+10);for (vector<int>::iterator i = v.begin(); i != v.end(); ++i)cout << *i << " ";cout << endl;typedef vector<int>::iterator vi;pair<vi, vi> range = find_equal_sequence(v.begin(), v.end(), 4);v.erase(range.first, range.second);for (vector<int>::iterator i = v.begin(); i != v.end(); ++i)cout << *i << " ";cout << endl;return 0;}