Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why no sort(v) in C++?

Tags:

c++

stl

I always wondered why there is no

sort(v);// same as std::sort(v.begin(),v.end())

If I recall correctly long time ago I saw a boostcon clip where speaker said that concepts are required for this, but I dont see why. BTW I tried this (in VS 11) and it works niceli from what I can see.

template <typename Container>
void sortfx(Container& c)
{
    std::sort(c.begin(),c.end());
}
int main()
{

    std::vector<double> v;
    //std::list<double> v; this causes compile errors
    v.push_back(1701);
    v.push_back(1729);
    v.push_back(74656);
    v.push_back(2063);
    sortfx(v);
    assert(std::is_sorted(begin(v),end(v)));

}

EDIT: Bjarne himself explains the concepts, with sort as an example :) https://www.informit.com/articles/article.aspx?p=2080042&WT.rss_f=Article&WT.rss_a=An%20Interview%20with%20Bjarne%20Stroustrup&WT.rss_ev=a

like image 741
NoSenseEtAl Avatar asked Jun 24 '12 02:06

NoSenseEtAl


1 Answers

It's not the std::sort(v) -> std::sort(v.begin(), v.end()) expansion that would need concepts, but the alternate sort function taking an additional parameter for the comparison - std::sort(v.begin(), v.end(), compare).

If you have a call std::sort(v, compare), the implementation would need concepts to distinguish it from std::sort(start, end) for a non-container.

The <algorithm> header is full of templates with this kind of problem.

like image 83
Bo Persson Avatar answered Nov 19 '22 18:11

Bo Persson