Arrays

Hello, If I have an int array with elements {1,2,3,4}

and I do not want to add the ints inside it but instead I want to have an int variable that holds the first 3 digits of the array for it to be int x = 123; and 123 being the first 3 elements{1,2,3} of the array, any ideas?

Basically instead of having 1 2 3 as separate digits in 3 separate indexes of the array I'd like to have 1 index OR variable that will be 123 as an actual 3 digit number.
Last edited on
using std::inner_product:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
#include <algorithm>

const int multipliers [] = {100, 10, 1};

int numberMaker(const int* ar)
{
    return std::inner_product (ar, ar + 3, multipliers, 0);
}
//http://en.cppreference.com/w/cpp/algorithm/inner_product

int main()
{
    int ar[] = {1, 2, 3, 4};
    std::cout << numberMaker(ar) << "\n";
}

if you don't want to (or indeed, can't) use the algorithm then you can write out the equivalent code in long-form:
1
2
3
4
5
6
7
8
9
10
int numberMaker(const int* ar)
{
   // return std::inner_product (ar, ar + 3, multipliers, 0);
    int number{};
    for (size_t i = 0; i < 3; ++i)
    {
        number += ar[i]*multipliers[i];
    }
    return number;
}


edit: also need to check that array ar does indeed have at least 3 elements
Last edited on
int first3( int *a ) { return 100 * a[0] + 10 * a[1] + a[2]; }
Also, as a reduction:
std::accumulate(a, a + 3, 0, [](int a, int b) { return a * 10 + b; });
mbozzi: you've pulled a neat trick with this one, i truly admire this elegant solution
Thanks for all the replies, managed to reach it in sort of another direct algorithm


1
2
3
4
5
6
7
8
9
int arr[5] = {1,2,3,4,5};
    int x = 0;

    for(int i = 0; i < 5; i++)
    {
        x *= 10;
        x += arr[i];
    }
    cout << x;
Last edited on
Topic archived. No new replies allowed.