Question: can you do this code faster? it need a better searching algorithm. you can oly use #include #include - - - - - - -

can you do this code faster? it need a better searching algorithm. you can oly use #include
#include
-----------
#include "trendtracker.h"
Trendtracker::Trendtracker(){
E.clear();
}
void Trendtracker::insert(std::string ht){
for (Entry& entry : E){
if (entry.hashtag == ht){
return;
}
}
Entry newEntry;
newEntry.hashtag = ht;
newEntry.pop =0;
E.push_back(newEntry);
}
int Trendtracker::size(){
return E.size();
}
void Trendtracker::tweeted(std::string ht){
for (Entry& entry : E){
if (entry.hashtag == ht){
entry.pop++;
return;
}
}
}
int Trendtracker::popularity(std::string ht){
for (const Entry& entry : E){
if (entry.hashtag == ht){
return entry.pop;
}
}
return -1;
}
std::string Trendtracker::top_trend(){
if (E.empty()){
return "";
}
int maxPop = E[0].pop;
std::string topHashtag = E[0].hashtag;
for (const Entry& entry : E){
if (entry.pop > maxPop){
maxPop = entry.pop;
topHashtag = entry.hashtag;
}
}
return topHashtag;
}
void Trendtracker::top_three_trends(std::vector& T){
// Sort the entries based on popularity
for (size_t i =0; i < E.size(); ++i){
for (size_t j = i +1; j < E.size(); ++j){
if (E[j].pop > E[i].pop){
std::swap(E[i], E[j]);
}
}
}
T.clear();
for (const Entry& entry : E){
T.push_back(entry.hashtag);
if (T.size()>=3){
break;
}
}
}
void Trendtracker::remove(std::string ht){
for (auto it = E.begin(); it != E.end(); ++it){
if (it->hashtag == ht){
E.erase(it);
break;
}
}
}
void Trendtracker::top_k_trends(std::vector& T, int k){
// Sort the entries based on popularity
for (size_t i =0; i < E.size(); ++i){
for (size_t j = i +1; j < E.size(); ++j){
if (E[j].pop > E[i].pop){
std::swap(E[i], E[j]);
}
}
}
T.clear();
for (const Entry& entry : E){
T.push_back(entry.hashtag);
if (T.size()>= k){
break;
}
}
}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!