Reputation: 391
UPDATED WITH FIX
I want to return only the number of unique entries in my array. The array contains a string variable that represents IP address. If there are 10 of them, but of 3 different kinds I just want to return 3. I have been at this all day and can't seem to figure out a solution that works. My code:
Original code
int getUnique(Visitors info[], string url, string startDate, string endDate){
int count = 0;
string temp;
for(int i = 0 ; i < N ; i++){
if(url == info[i].URL && (dateChecker(startDate, endDate, info[i].dateAccessed))){
}
}
return count;
}
Updated code
int getUnique(Visitors info[], string url, string startDate, string endDate){
set<string> ips;
for(int i = 0 ; i < N ; i++){
if(url == info[i].URL && (dateChecker(startDate, endDate, info[i].dateAccessed))){
ips.insert(info[i].IP);
}
}
return ips.size();
}
The first if checks whether the matching URL does in fact match, and the dateChecker
just makes sure that the date that the particular IP went to that URL is in between the 2 passed dates (startDate
and endDate
). How do I get the number of different IPs under these conditions?
Upvotes: 2
Views: 1379
Reputation: 4463
As already mentioned you need to use std::set however there is no need to manually iterate array, since std::map accepts iterators to range it should be constructed from. Thus
std::map<std::string> unique(strinvec.begin(), stringvec.end());
Should do the trick.
And if you need to know only count of unique elements, you may use even shorter notation.
size_t unique_count = std::map<std::string>(strinvec.begin(), stringvec.end()).size();
Upvotes: 1
Reputation: 158459
You could use a std::set
to keep track of unique string
s:
std::set<std::string> mySet ;
for each iteration just do:
mySet.insert( info[i].IP) ;
and at the end:
return mySet.size() ;
Upvotes: 1
Reputation: 56479
Use std::set
, it stores items uniquely and it's efficient:
std::set<string> ips;
for (int i=0; i<N; i++)
ips.insert(info[i].IP);
int unique_ips = ips.size();
Upvotes: 2
Reputation: 5988
You can do this lazily with set
std::set<string> uniq;
if(url == info[i].URL && (dateChecker(startDate, endDate, info[i].dateAccessed))){
uniq.insert(info[i].URL);
}
return uniq.size();
Upvotes: 1