Reputation: 55
Hi I have this function that gets the unique elements from a vector, but I was wondering how can make it get me the number of those unique elements as well.
void getUniqueSellers(vector<string> & result) {
vector<CService>::iterator i= m_vData.begin();
while(i != m_vData.end()) {
if(find(result.begin(), result.end(), (*i).GetSeller()) == result.end()) {
result.push_back((*i).GetSeller());
}
i++;
}
}
void main()
{
vector<string> res;
myAnalyzer.getUniqueSellers(res);
vector<string>::iterator i=res.begin();
while(i!=res.end()) {
cout<< *i<<",";
i++;
}
system("pause");
return;
}
Upvotes: 1
Views: 1427
Reputation: 61900
Since you already have a list of them, it's easy to find the size:
res.size()
However, I suggest you drop the recreated algorithm to do it and use an existing one. I also suggest you return a value instead of using an out parameter:
std::vector<std::string> getUniqueSellers() {
std::sort(m_vData.begin(), m_vData.end());
m_vData.erase(std::unique(m_vData.begin(), m_vData.end()), m_vData.end());
std::vector<std::string> res;
std::transform(m_vData.begin(), m_vData.end(), std::back_inserter(res), [](const CService &cs) {return cs.GetSeller();});
return res;
}
I used a C++11 lambda, so you can replace that with a normal functor if you don't have C++11. This also requires you to implement equality for CService
based on GetSeller()
. Alternatively, if you don't want to modify m_vData
, you can make a copy or use std::set
:
std::set<std::string> res;
std::transform(m_vData.begin(), m_vData.end(), std::back_inserter(res), [](const CService &cs) {return cs.GetSeller();});
return std::vector(res.begin(), res.end());
Upvotes: 3
Reputation: 31184
Instead of returning a vector of string, you can make a class of seller
that contains a string name
and an int count
. and return a vector of that.
If you find a duplicate, instead of ignoring it, you can just incriment the count
Upvotes: 0