//NameHash.h
//NameHash.cppclass NameHash{ public: NameHash(void); ~NameHash(void); int getValue(char name){return name_value[name-'A'];} private: int name_value[27]; };
#include "stdafx.h" #include "NameHash.h" #include <iostream> NameHash::NameHash(void) { for(int i='A'-'A';i<='Z'-'A';i++) { int tmp=i/3+2; if(tmp>9) tmp-=10; name_value[i]=tmp; } } NameHash::~NameHash(void) { } //int main(int args[]) //{ // NameHash namehash=NameHash(); // for(char ch='A';ch<='Z';ch++){ // std::cout<<ch<<" "<<namehash.getValue(ch)<<" "; // } // std::cout<<std::endl; // // //}
// ConsoleApplication4.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <algorithm> #include <iostream> #include <hash_map> #include <string> #include <sstream> #include "NameHash.h" using namespace std; class Person{ public: Person(){ name=""; value=""; } Person(string strname){ name=strname; setValue(); } ~Person(){ //delete this; } string getValue() const {return value;} string getName() const {return name;} //int compare(Person &p1); private: NameHash namehash; string name; string value; void setValue(); //int hashValue(); }; void Person::setValue() { stringstream strStream; //cout<<name.length()<<endl; for(int i=0;i<name.length();i++) { //cout<<namehash.getValue(name[i])<<" "; strStream<<namehash.getValue(name[i]); } value=strStream.str(); //cout<<value<<endl; } int compare(const void *p1,const void *p2) { Person *tp1=(Person *)p1; Person *tp2=(Person *)p2; if(tp1->getValue()>tp2->getValue()) return 1; if(tp1->getValue()<tp2->getValue()) return -1; if(tp1->getValue()==tp2->getValue()) { if(tp1->getName()>tp2->getName()) return 1; if(tp1->getName()==tp2->getName()) return 0; else return -1; } } int main(int argc, _TCHAR* argv[]) { string pername[10]={"LISK","MIKE","JOEN","ANNA","JHSK","PETER","VIVI","DAWN","LILY","LUCY"}; Person p[10]; for(int i=0;i<10;i++) { p[i]=Person(pername[i]); } qsort(p,10,sizeof(p[0]),compare); int i=0; //每个元素与其后元素比较,输出相同值,一直比较到倒数第二个元素为止,最后一个元素不用比较,否则数组越界 while(i<9) { int j=i+1; while(p[j].getValue()==p[i].getValue()) { cout<<p[i].getValue()<<" "; cout<<p[j].getValue()<<" "<<p[j].getName()<<endl; j++; } i=j; //cout<<p[i].getValue()<<endl; } /*hash_map<int,string> phoneMap; string pername[10]={"LISK","MIKE","JOEN","ANNA","JHSK","PETER","VIVI","DAWN","LILY","LUCY"}; Person **p=new Person *[10]; for(int i=0;i<10;i++) { p[i]=new Person(pername[i]); int key=atoi(p[i]->getValue().c_str()); string value=p[i]->getName(); phoneMap[key]=value; } for(hash_map<int,string>::iterator it=phoneMap.begin();it!=phoneMap.end();it++) { cout<<it->first<<" "<<it->second<<endl; }*/ /*Person *p1=new Person("LISK"); int key=atoi(p1->getName().c_str()); string value=p1->getValue(); phoneMap[key]=value;*/ //cout<<p1->getValue(); return 0;
}
编程珠玑第二章第六题--利用标记输出同类元素
最新推荐文章于 2020-09-21 20:55:00 发布