char* findMostlyBroughtItem(char* shippingRecordArray[], int length, char* givenItem);
inline bool isSpace(char x){
return x == ' ' || x == '\r' || x == '\n' || x == '\f' || x == '\b' || x == '\t';
}
char* rightTrim(char *str){
int len = strlen(str);
while(--len>=0){
if(isSpace(str[len])){
str[len] = '\0';
}else{
break;
}
}
return str;
}
char * getInputLine(char *buffer, int length){
if(fgets(buffer,length, stdin)==NULL){
return NULL;
}
rightTrim(buffer);
if(strlen(buffer)<=0){
return NULL;
}
return buffer;
}
int splitAndConvert(char* strings,char* array[]){
char* tokenPtr = strtok(strings," ");
int i=0;
while(tokenPtr!=NULL){
array[i] = tokenPtr;
i++;
tokenPtr=strtok(NULL," ");
}
return i;
}
int main() {
char givenItem[1000] = {0} ;
while(getInputLine(givenItem, 1000)){
char line[1000];
getInputLine(line, 1000);
char* shoppingRecordArray[1000] = {0};
int length = splitAndConvert(line,shoppingRecordArray);
if(length==0){
break;
}
char * item = findMostlyBroughtItem(shoppingRecordArray, length, givenItem);
if (NULL != item)
{ // 原来系统提供的代码。这里没有NULL判断
cout<<item<<endl;
free(item); // 自己加的
}
}
return 0;
}
char* findMostlyBroughtItem(char* shoppingRecordArray[], int length, char* givenItem){
if(NULL==shoppingRecordArray || NULL==givenItem || length <=0)
return NULL;
multimap mymap;
multimap::iterator mapit;
multimap::iterator mapit2;
map buymap;
map::iterator itbuymap;
for(int i=0;i
string customer(shoppingRecordArray[i++]);
string item(shoppingRecordArray[i]);
mymap.insert(make_pair(customer,item));
}
string searchitem(givenItem);
for(mapit=mymap.begin();mapit!=mymap.end();mapit++){
//item found
if(searchitem==mapit->second) {
for(mapit2=mymap.begin();mapit2 != mymap.end();mapit2++) {
if(mapit->first==mapit2->first) {
itbuymap=buymap.find(mapit2->second);
if(itbuymap==buymap.end())
buymap.insert(make_pair(mapit2->second,1));
else
buymap[mapit2->second]++;
}
}
}
}
pair founditem("",0);
for(itbuymap=buymap.begin();itbuymap!=buymap.end();itbuymap++){
if(itbuymap->first !=searchitem && itbuymap->second > founditem.second)
founditem=make_pair(itbuymap->first,itbuymap->second);
}
char *p=NULL;
if(founditem.first != "") {
cout <<founditem.first<<endl;
p=new char[founditem.first.length()+1];
strcpy(p,founditem.first.c_str());
}
return p;
}