请问一个vector<string,int>按string如何排序
#include <iostream>
#include <String>
#include <vector>
#include <algorithm>
using namespace std;
struct Pair
{
string word;
int times;
};
vector <Pair> word_count;
int& tms(const string& s)
{
for (unsigned int i=0; i <word_count.size(); i++)
if (s==word_count[i].word)
return word_count[i].times;
Pair p = {s,0};
word_count.push_back(p);
return (word_count.end()-1)-> times;
}
bool sort_r(const Pair& w1,const Pair& w2)
{
return w1-> word <w2-> word;
}//注意这个函数有问题
void main()
{
//cout < <( "ab "> "ac ") < <endl;
string buf;
while (cin> > buf)
{
if ( "Quit "!=buf)
tms(buf)++;
else
break;
}
sort(word_count.begin(),word_count.end(),sort_r);//请问如何使用?
for (vector <Pair> ::const_iterator ptr=word_count.begin();ptr <word_count.end();++ptr)
cout < <ptr-> word < < ": " < <ptr-> times < <endl;
}
想对vector类型的word_count根据其中string类型的word进行排序,请尽量使用标准库,再加自定义的方法更佳,第一个给出标准库算法者得分。谢谢!
[解决办法]
重载一下Pair结构的比较函数就可以了
[解决办法]
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;
}
[解决办法]
关注
请教一个vector<string,int>按string怎么排序
请问一个vectorstring,int按string如何排序#includeiostream#includeString#includevector#includ
