练习一:
#include <iostream>
#include <set>
using namespace std;class Complex
{int key;double real;double vir;
public:Complex(int key):key(key){}Complex(int key,double real,double vir):key(key),real(real),vir(vir){}bool operator<(const Complex &other){return real < other.real && vir < other.vir;}bool operator<(const Complex &other) const{return this->key < other.key;}void show()const{cout << real << " + "<< vir << "i" << endl;}void set_real(double real){this->real = real;}void set_vir(double vir){this->vir = vir;}
};int main()
{set<Complex> myset;myset.insert(Complex(1,1,1));myset.insert(Complex(2,2,1));myset.insert(Complex(3,3,1));myset.insert(Complex(4,4,1));myset.insert(Complex(5,5,1));myset.insert(Complex(6,6,1));myset.insert(Complex(7,7,1));pair<set<Complex>::iterator,bool> p1 = myset.insert(Complex(5,5,5));p1.first->show();cout << p1.second << endl;cout << "*********************" << endl;myset.erase(Complex(7));set<Complex>::iterator tar = myset.find(Complex(3));tar->show();const_cast<Complex &>(*tar).set_real(88.88);const_cast<Complex &>(*tar).set_vir(66.66);cout << "*********************" << endl;for(auto ele:myset){ele.show();}return 0;
}
练习二:
#include <iostream>
#include <set>
using namespace std;class character_count
{char ch;int count;
public:character_count(char c):ch(c),count(1){}char get_ch(){return ch;}int get_count(){return count;}void add_count(){count++;}void add_count()const{const_cast<character_count *const>(this)->add_count();}bool operator<(const character_count &other) const{return this->ch < other.ch;}void show(){cout << "字符:" << ch<< " 出现 " << count << "次"<< endl;}
};int main()
{string str;set<character_count> myset;cin >> str;//以上述代码为基础输出str中每一个字符出现了几次
#if 0//方法一:for(char c:str){set<character_count>::iterator it = myset.find(character_count(c));if(it != myset.end()){const_cast<character_count&>(*it).add_count();}else{myset.insert(character_count(c));}}
#else//方法二:for(char c:str){pair<set<character_count>::iterator,bool> p = myset.insert(character_count(c));if(p.second == 0){(*p.first).add_count();}/*std::pair<iterator, bool>insert(const value_type& __x){std::pair<typename _Rep_type::iterator, bool> __p = _M_t._M_insert_unique(__x);return std::pair<iterator, bool>(__p.first, __p.second);}template<typename _T1, typename _T2>struct pair{typedef _T1 first_type; /// @c first_type is the first bound typetypedef _T2 second_type; /// @c second_type is the second bound type…………*/}
#endiffor(auto ele:myset){ele.show();}return 0;
}