请教一个vector<string,int>按string怎么排序
1个回答
展开全部
struct MyStruct
{
MyStruct(const string& s, int iTimes):m_strWord(s), m_iTimes(iTimes){}
string m_strWord;
int m_iTimes;
friend bool operator < (const MyStruct& s1, const MyStruct& s2);
};
bool operator < (const MyStruct& s1, const MyStruct& s2)
{
//添加比较规则,
return s2.m_strWord.compare(s1.m_strWord) == 1;
}
vector <MyStruct> word_count;
int& tms(const string& s)
{
for (size_t i= 0; i < word_count.size(); i++)
{
if (s == word_count[i].m_strWord)
return word_count[i].m_iTimes;
}
MyStruct p(s, 0);
word_count.push_back(p);
return (word_count.end()-1)-> m_iTimes;
}
void main()
{
string buf;
while (cin> > buf)
{
if ( "Quit "!=buf)
tms(buf)++;
else
break;
}
sort(word_count.begin(), word_count.end());
vector <MyStruct> ::iterator it = word_count.begin();
for (; it < word_count.end(); it++)
cout < <it-> m_strWord < < ": " < <it-> m_iTimes < <endl;
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询