C++ – Convert vector to a single number

There is a method to convert a std::vector<uint64> to a single number?

I have a vector like this:

v[0] = 0;
v[1] = 6796890219657246832;

Or like this:

v[0] = 16377;
v[1] = 2631694347470643681;
v[2] = 11730294873282192384;

The result I like to get is, in the first case 6796890219657246832 and in the second: 16377263169434747064368111730294873282192384. My main problem is choosing the data type for the value as it is possible that the vector size is not always 2 but it could be 5 or higher.

Answer

No C++ provided types will support that many digits. So obviously, you need BIG-INT for that. Ethier implemented by yourself or using a tested library like GMP.

For example, using GMP will be like:

static mpz_class convert_to_i(std::vector<std::size_t> const& vec)
{
        std::string sum;
        for (auto const number : vec) {
                sum += std::to_string(number);
        }
        return mpz_class(sum);
}

Let the vec be:

std::vector<std::size_t> const vec = {
        16377,
        2631694347470643681,
        1173029487328219238
};

Result of convert_to_i(vec) will be:

1637726316943474706436811173029487328219238

If your original numbers are also big-int:

static mpz_class convert_to_i(std::vector<mpz_class> const& vec)
{
        std::string sum;
        for (auto const& number : vec) {
                sum += number.get_str();
        }
        return mpz_class(sum);
}

Let the vec_2 be:

std::vector<mpz_class> const vec_2 = {
        mpz_class("26316943474706436812631694347470643681"),
        mpz_class("263169434747064368126316943474706436812631694347470643681")
};

Result of convert_to_i(vec_2) will be:

26316943474706436812631694347470643681263169434747064368126316943474706436812631694347470643681

Just for copy/paste and test: the code.