I want to read a set of keywords and store them in size order, and if you type same keywords twice, i can only store only once, so naturally, I want to store string using set<string> it can remove duplicate for me, however, I have to override < to get string stored in size order.
for example:
if the input are:"he" "helo" "hello" "he" "helloworld"
then the set should contain
"helloworld"
"hello"
"helo"
"he"
but the code I write sames to have a problem processing two strings with same size.
like input "a" "b" "c" "a"
instead of a set of{"a", "b", "c"}, i get {"a", "b", "c", "a"}, very confusing.
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 51 52 53 54 55 56 57 58 59 60 61
|
#include <iostream>
#include <vector>
#include <string>
#include <set>
using namespace std;
struct word{
string keyword;
word(string keyword){
this->keyword = keyword;
}
bool operator<(const struct word& right) const{
cout<<"current word:"<<this->keyword<<endl;
cout<<"right word:"<<right.keyword<<endl;
cout<<"Are they the same? 0:same"<<this->keyword.compare(right.keyword)<<endl;
if(this->keyword.size() == right.keyword.size()){
return this->keyword.compare(right.keyword);
} else {
return this->keyword.size() > right.keyword.size();
}
}
};
class Solution{
public:
int add(string input){
word str(input);
keywords.insert(str);
return keywords.size();
}
void show(void) {
for(auto str:keywords) {
cout<<str.keyword;
}
cout<<endl;
}
private:
set<word> keywords;
};
int main() {
int num;
cin>>num;
Solution solu;
for (int i = 0; i < num; i++) {
int opType;
cin>>opType;
cin.get();
string str;
getline(cin, str);
switch(opType) {
case 1:
cout<<solu.add(str)<<endl;
solu.show();
break;
default:
break;
}
}
}
|