c++ - vector sort and erase won't work -


when using code remove duplicates invalid operands binary expression errors. think down using vector of struct not sure have googled question , code on , on again suggests code right isn't working me.

std::sort(vec.begin(), vec.end()); vec.erase(std::unique(vec.begin(), vec.end()), vec.end()); 

any appreciated.

edit:

filesize = textfile.size(); vector<wordfrequency> words (filesize); int index = 0; for(int = 0; <= filesize - 1; i++) {     for(int j = 0; j < filesize - 1; j++)     {         if(string::npos != textfile[i].find(textfile[j]))         {             words[i].word = textfile[i];             words[i].times = index++;         }     }     index = 0; }  sort(words.begin(), words.end()); words.erase(unique(words.begin(), words.end(), words.end())); 

first problem.

unique used wrongly

unique(words.begin(), words.end(), words.end())); 

you calling 3 operand form of unique, takes start, end, , predicate. compiler pass words.end() predicate, , function expects comparison functor. obviously, isn't one, , enter happy world of c++ error messages.

second problem.

either use predicate form or define ordering

see definitions of sort , unique.

you can either provide

bool operator< (wordfrequency const &lhs, wordfrequency const &rhs) {     return lhs.val_ < rhs.val_; } 

, if less-than operation makes sense type, i.e. if there natural ordering, , if it's not arbitrary (maybe want other sort orders in future?).

in general case, use predicate forms sorting:

auto pred = [](wordfrequency const &lhs, wordfrequency const &rhs) {     return lhs.foo < rhs.foo; };  sort (words.begin(), words.end(), pred); words.erase (unique (words.begin(), words.end(), pred)); 

if can't c++11, write functor:

struct freqascending { // should make adaptible std::binary_function     bool operator() (wordfrequency const &lhs, wordfrequency const &rhs) const     { ... }; }; 

i guess in case ("frequency of words"), operator<makes sense.

also note vector::erase: remove element indicated passed iterator. but, see std::unique, unique returns iterator new end of range, , not sure if want remove new end of range. mean?

words.erase (words.begin(),              unique (words.begin(), words.end(), pred)); 

third problem.

if need top ten, don't sort

c++ comes different sorting algorithms (based on this). top 10, can use:

this wastes less watts on cpu, contribute overall desktop performance, , laptop batteries last longer can more sorts.


Comments

Popular posts from this blog

jasper reports - Fixed header in Excel using JasperReports -

media player - Android: mediaplayer went away with unhandled events -

python - ('The SQL contains 0 parameter markers, but 50 parameters were supplied', 'HY000') or TypeError: 'tuple' object is not callable -