std::sort question

R

Ravi

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? 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? How to resolve this problem?

Thanks.
 
R

Rolf Magnus

Ravi said:
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?

You don't need to, and actually shouldn't do it.
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?

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.
How to resolve this problem?

Remove the <unsigned char*>.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Staff online

Members online

Forum statistics

Threads
474,162
Messages
2,570,893
Members
47,432
Latest member
GTRNorbert

Latest Threads

Top