0

From the usage of Sort(begin,end) it appears that by just specifying the containers beginning and ending index the function can sort a container. But my question how does the sort function gets the type of containers.

std::sort(myvector.begin(), myvector.end());

From the above code I assume the starting and end index is send. How come the vector type and the vector name is deduced.

1
  • 3
    The algorithm doesn't care about the type of container - only the type of iterators. It requires RandomAccessIterators, which is why you cannot use std::sort with a std::list Commented Jan 11, 2014 at 3:03

2 Answers 2

7

The function std::sort, like many others from <algorithm>, does not care about the container type because it works with concepts.

Specifically, the function is defined as:

template< class RandomIt >
void sort( RandomIt first, RandomIt last );

As you can see, templates are used to express the concept of ValueSwappable and RandomAccessIterator iterators.

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

3 Comments

Sorry Could not understand could you please elaborate a little more
Also if it doesn't care about the container type how can a sort function compare values.
@krish_oza, read about templates and then the links I've added in my answer. Everything will be clear.
1

myvector.begin()/end() returns type "containertype::iterator"

As to how the sort() works, it actually doesn't care about the underlying container type, as long as the two elements in the container are comparable (either less<type>() exist for that element, or you specify your own comparing function).

3 Comments

The "comparable" requirement is definitely not the only one.
@Jefffrey What else? iterator being RandomAccessIterator / two iterators within the same container?
Take a look at the links in my answer (specifically the ValueSwappable and RandomAccessIterator requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.