问题
使用链表类型list或forward_list成员函数算法时,其会改变底层的容器.这样做,会让指向被删除元素的迭代器、引用和指针都会失效!而使用失效的迭代器、指针或引用时严重的运行时错误!!
使用list成员函数算法编写一个单词去重的程序.
源代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | /************************************************************************* > File Name: test.10.42.cpp > Author: puruidong > Mail: 1@w1520.com > Created Time: 2014年06月24日 ************************************************************************/ #include<iostream> #include<list> #include<algorithm> #include<functional> using namespace std; using namespace std::placeholders; /**************************************** 使用list成员函数算法编写一个单词去重的程序. ****************************************************/ bool issh(const string &s1,const size_t sz) { return s1.size()>sz; } //使用成员函数算法. void elis(list<string> &lst,size_t sz) { lst.sort(); lst.unique(); auto rf = find_if(lst.begin(),lst.end(),bind(issh, _1 , sz )); //auto ws = lst.end()-rf; cout << "******************************\n下面是大于" << sz << "的元素\n**********************************" << endl; for_each(rf,lst.end(),[](const string &a){ cout << a << " ";}); cout << endl; } int main() { cout << "使用list替代vector实现去重的程序:" << endl; string pa; list<string> lst; while(cin >> pa) { lst.push_back(pa); } elis(lst,5); return 0; } |