<Functional>: plus<long>() on integers gives unexpected result

I don’t understand why I do not get the same results in these two cases:

#include <iostream>
#include <vector>
#include <numeric> // for accumulate
#include <functional> // for plus()
using namespace std;

int main() {
    long long i = (long long)  0xFFFFFFFF + 2;
    cout << i << endl;

    vector<int> v;
    v.push_back(0xFFFFFFFF);
    v.push_back(2);

    long long r = accumulate(v.begin(), v.end(), 0, plus<long long>());
    cout << r << endl;

    return 0;
}

Anyone any ideas?

EDIT: as correctly pointed out below, this is due to the sign bit in int I wasn't counting on. 0x7FFFFFFF would obviously be better for testing. Also, I erroneously expected that the return type of plus() would be the same as for accumulate(), which is not the case: it is based on the third argument.

Answers


There are two problems here:

  1. The number 0xFFFFFFFF won't fit in an int (assuming 32-bit ints), so the value stored in the vector is actually -1 on most implementations. Using vector<unsigned int> or vector<long long> should fix this.

  2. The type returned by accumulate is the type deduced from the third parameter. Since you passed in 0, this will be int. You should pass in 0LL instead so that it returns long long.

This program with both fixes will return the correct result:

#include <iostream>
#include <vector>
#include <numeric> // for accumulate
#include <functional> // for plus()
using namespace std;

int main() {
    long long i = (long long)  0xFFFFFFFF + 2;
    cout << i << endl;

    vector<long long> v; //or vector<unsigned int>
    v.push_back(0xFFFFFFFF);
    v.push_back(2);

    long long r = accumulate(v.begin(), v.end(), 0LL, plus<long long>());
    cout << r << endl;

    return 0;
}

Need Your Help

Releasing an object with NSDate object as property

objective-c memory-management nsdate

I created an object with a NSDate property like this:

Failed to compile lua in windows phone 8 system

windows-phone-8 lua cocos2d-x

We are working on IOS and Android with cocos2dx, we have lots of lua script in our codes, and it working well in the IOS and Android. now we plan porting the app to Windows Phone 8 or Windows RT.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.