1、rbegin、rend——容器逆序输出的头和尾
#include <iostream> #include <set> #include <iomanip> #include <string> using namespace std; template <class T> class Member { public: Member(T l, T f) : last(l), first(f) {} void print() const // const !!! { cout.setf(ios::left); cout << setw(15) << first.c_str() << last << endl; } private: T first, last; // const !!! friend bool operator < (const Member& m1, const Member& m2) { return (m1.last < m2.last) ? true : false; } friend bool operator == (const Member& m1, const Member& m2) { return (m1.last == m2.last) ? true : false; } }; //=============================================== int main () { typedef Member<string> M; typedef set<M, less<M> > S; M m("Frost","Robert"); S s; s.insert(m); s.insert(M("Smith","John")); s.insert(M("Amstrong","Bill")); s.insert(M("Bain","Linda")); S::iterator It = s.begin(); while ( It != s.end() ) (It++)->print(); cout << endl; S::reverse_iterator rI = s.rbegin(); while ( rI != s.rend() ) (rI++)->print(); return 0; } 运行结果: // Bill Amstrong // Linda Bain // Robert Frost // John Smith // // John Smith // Robert Frost // Linda Bain // Bill Amstrong
2、size——返回容器内元素的个数
#include <iostream> #include <set> using namespace std; void print (set<int, less<int> >& s) { set<int, less<int> >::iterator It; for ( It = s.begin(); It != s.end(); It++ ) cout << *It << " "; cout << endl; } //-------------------------------------------- int main () { int ary[] = {1,2,3,2,3,4,8,2,5,6}; set<int, less<int> > s; s.insert(ary,ary+10); cout << "Size of set s = " << s.size() << endl; print(s); s.clear(); cout << "Size of set s = " << s.size() << endl; return 0; } 运行结果: // Size of set s = 7 // 1 2 3 4 5 6 8 // Size of set s = 0
3、swap——将自身容器的内容与指定容器的内容交换
#include <iostream> #include <set> #include <algorithm> using namespace std; void print (set<int, less<int> >& s) { copy(s.begin(),s.end(), ostream_iterator<int>(cout," ")); cout << endl; } //-------------------------------------------- int main () { int ary1[] = {1,2,3,2,3,4,8,2,5,6}; int ary2[] = {5,0,9,2,3,4,8,2,5,6}; set<int, less<int> > s1, s2; s1.insert(ary1,ary1+10); cout << "s1 : "; print(s1); cout << "s2 : "; s2.insert(ary2,ary2+10); print(s2); if ( s1 != s2 ) s1.swap(s2); cout << "s1 : "; print(s1); cout << "s2 : "; print(s2); return 0; } 运行结果: // s1 : 1 2 3 4 5 6 8 // s2 : 0 2 3 4 5 6 8 9 // s1 : 0 2 3 4 5 6 8 9 // s2 : 1 2 3 4 5 6 8
4、返回一个用于比较元素间的值的函数对象
#include <iostream> #include <set> using namespace std ; template void truefalse(T t) { cout << (t?"True":"False") << endl; } int main () { set<int> s; cout << "s.value_comp()(1,2) returned "; truefalse(s.value_comp()(1,2)); // True cout << "s.value_comp()(2,1) returned "; truefalse(s.value_comp()(2,1)); // False cout << "s.value_comp()(1,1) returned "; truefalse(s.value_comp()(1,1)); // False return 0; } 运行结果: // s.value_comp()(1,2) returned True // s.value_comp()(2,1) returned False // s.value_comp()(1,1) returned False
除非注明,文章均为CppLive 编程在线原创,转载请注明出处,谢谢。