Why is the return type of count_if() "signed" rather than "unsigned"?

X

xmllmx

As we know, count_if() will never return a negative number. So, it
seems evident that the return type of count_if() should be "unsigned
integral type" rather than "signed integral type".

However, to my surprise, the C++ standard should define the return
type is "signed integer type", which causes a lot of conceptual
confusions and annoying compiling warnings such as "signed/unsigned
mismatch".

What's the rationale for the C++ standard committee to do so ?

Thanks in advance!
 
B

Bo Persson

xmllmx said:
As we know, count_if() will never return a negative number. So, it
seems evident that the return type of count_if() should be "unsigned
integral type" rather than "signed integral type".

However, to my surprise, the C++ standard should define the return
type is "signed integer type", which causes a lot of conceptual
confusions and annoying compiling warnings such as "signed/unsigned
mismatch".

What's the rationale for the C++ standard committee to do so ?

Thanks in advance!

The distance between two iterators is signed, because in the general
case it could be negative. Here it can not, but count_if still uses
the difference_type, to be consistent with other algorithms using
iterators.


Bo Persson
 
S

Saeed Amrollahi

Hi

As we know, count_if() will never return a negative number. So, it
seems evident that the return type of count_if() should be "unsigned
integral type" rather than "signed integral type".

However, to my surprise, the C++ standard should define the return
type is "signed integer type", which causes a lot of conceptual
confusions and annoying compiling warnings such as "signed/unsigned
mismatch".

According to C++ standard document, the return type of count/count_if
is: iterator_traits<InputIterator>::difference_type.
Because it's like the distance of two pointers
it's may be positive or negative. However count_if accepts Input
Iterator
so such difference is always positive.

Frankly, I don't think the following code issues a lot of annoying
warnings:

#include <algorithm>
#include <vector>
#include <iostream>
bool is_odd(int i) { return i % 2 != 0; }
int main()
{
using namespace std;
vector<int> v;
for (int i = 0; i < 1000; ++i)
v.push_back(i);

int c = count_if(v.begin(), v.end(), is_odd);

cout << c << '\n';
return 0;
}

I compiled and ran using VS 2008 (VC++ 9).
What's the rationale for the C++ standard committee to do so ?

Thanks in advance!

Regards,
-- Saeed Amrollahi
 

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

Members online

Forum statistics

Threads
473,994
Messages
2,570,222
Members
46,810
Latest member
Kassie0918

Latest Threads

Top