| re: std::sort question
Ravi wrote:
[color=blue]
> I came across code which contains:
>
> std::sort<unsigned char*>((newAnswer.begin()+1),newAnswer.end());
>
> with newAnswer defined as
>
> std::vector<unsigned char>& newAnswer
>
> However upon attempting to compile the above code I got the following
> errors (I am using g++ ver 3.3.1 on Cygwin)
>
>
> error: cannot convert `
> __gnu_cxx::__normal_iterator<unsigned char*, std::vector<unsigned
> char, std::allocator<unsigned char> > >' to `unsigned char*' for
> argument
> `1' to `
> void std::sort(_RandomAccessIter, _RandomAccessIter) [with
> _RandomAccessIter
> = unsigned char*]'
>
>
> My questions are:
>
> 1. Why do we need to specify <unsigned char*> when calling sort?[/color]
You don't need to, and actually shouldn't do it.
[color=blue]
> I have seen many exmaples where std::sort is called as
>
> std::vector<int> v;
> //populate v
> std::sort(v.begin(),v.end())
>
> 2. What does the above error message mean?[/color]
It's just because you specified <unsigned char*>. The template parameter
to std::sort is supposed to be an iterator, but you forced it to be a
pointer. For arrays, a pointer would be correct, and on some platforms,
also for vectors, but that's not guaranteed, and actually isn't the
case in g++'s standard library implementation.
[color=blue]
> How to resolve this problem?[/color]
Remove the <unsigned char*>. |