2
#include <stack> #include <list> #include <string> #include <iostream> #include <algorithm> #include <vector> #include <numeric> using namespace std; void biggies(vector<string>& str,vector<string>::size_type sz) { sort(str.begin(),str.end()); auto end_unique=unique(str.begin(), str.end()); str.erase(end_unique,str.end()); //When I remove the "const" in the parameter list, the code can't compile stable_sort(str.begin(), str.end(), [](const string&a,const string&b){return a.size()<b.size();}); auto wc=find_if(str.begin(), str.end(), [sz](string& a){return a.size()>=sz;}); for_each(wc, str.end(), [](string& s){cout<<s<<endl;}); } int main() { vector<string>vec{"11","22","1","1111","2222","2","111","222"}; biggies(vec, 2); } 

I test the code in Xcode 6.4 and Visual Studio 2015 and it turns out that both cannot compile without the "const" in the parameter list. I wonder why the lack of "const" would disrupt the compilation? I'll be very thankful with your answers.

3
  • Can you add what you get when trying to compile it? Commented Aug 5, 2015 at 6:38
  • 1
    It wouldn't make sense for a comparator to change the things it compares, so I at least the compilation error is a good thing. Commented Aug 5, 2015 at 6:39
  • @MKII there're errors in <algorithm >: No matching function for call to object of type... Commented Aug 5, 2015 at 6:43

1 Answer 1

1

I can't find anything in the standard (N3337) that puts any specific requirements on the parameter types for a comparator passed to sorting-related algorithms. All I can find that kind of hints at why you're having this issue is this:

25.4.2: It is assumed that comp will not apply any non-constant function through the dereferenced iterator.

It is somewhat indirect, but since it is 'assumed' that your comparator won't apply any non-const function to what's given to you by the algorithm, I guess it's valid that the algorithm pass const objects to it; this is likely the source of your problem.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.