470,594 Members | 1,120 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 470,594 developers. It's quick & easy.

How to pass a third argument to compare function?

I defined a class:

class inverted_index
{
private:
std::map<std::string, std::vector<size_t index;
public:
std::vector<size_tintersect(const std::vector<std::string>&);
};

bool compare(const std::string&, const std::string&);

vector<size_tinverted_index::intersect(const vector<string>& query)
{
sort(query.begin(), query.end(), compare);
vector<size_tresult = index[query.front()];

return result;
}

bool compare(const string& s1, const string& s2)
{
return index[s1].size() < index[s2].size();
}

In the intersect function, I want to sort the query by the
string matching vector size. So I define a compare function fort
'sort'.

I think I can't define compare as member function of inverted_index,
there is a current object as a implicit parameter for member
functions.
And the compare will have three parameters. I think it's wrong!

But if I define compare as a nonmember function with two parameters,
how can it access the index object. Make it 'friend' is useless here.
Jun 27 '08 #1
1 2282
On Jun 23, 7:08*pm, Lambda <stephenh...@gmail.comwrote:
I defined a class:

class inverted_index
{
private:
* * * * std::map<std::string, std::vector<size_t index;
public:
* * * * std::vector<size_tintersect(const std::vector<std::string>&);

};

bool compare(const std::string&, const std::string&);

vector<size_tinverted_index::intersect(const vector<string>& query)
{
* * * * sort(query.begin(), query.end(), compare);
* * * * vector<size_tresult = index[query.front()];

* * * * return result;

}

bool compare(const string& s1, const string& s2)
{
* * * * return index[s1].size() < index[s2].size();

}

In the intersect function, I want to sort the query by the
string matching vector size. So I define a compare function fort
'sort'.

I think I can't define compare as member function of inverted_index,
there is a current object as a implicit parameter for member
functions.
And the compare will have three parameters. I think it's wrong!

But if I define compare as a nonmember function with two parameters,
how can it access the index object. Make it 'friend' is useless here.
a compare functor could help you here. Pls find sample code below

Class Compare
{
public:
Compare(const int size)
: size_(size) {} // this could be your required size or so

bool operator()(const std::string &lhs, const std::string &rhs)
{
//your compare here
}

private:
const int size_;
};

Thanks,
Balaji.
Jun 27 '08 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by LuB | last post: by
5 posts views Thread by wilson | last post: by
14 posts views Thread by Abhi | last post: by
28 posts views Thread by Bill | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.