setting array to int

closed account (Dy7SLyTq)
lets say i have an array with the values 1, 5, 9, and 3. is there anyway to make this so i can have an int with the value 1593 based on those numbers in the array?
The number 1593 can be made by summing each digit multiplied by its place:
1*1000+
5*100+
9*10+
3*1=
1593
Here are two approaches: one with using a standard algorithm and the other with using the for statement based on range.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <iostream> 
#include <vector> 
#include <numeric>   

int main() 
{
         std::vector<int> v = { 1, 5, 9, 3 };
         const int base = 10;

         int x = std::accumulate( v.begin(), v.end(), 0, 
                                  []( int s, int i ) { return ( s * base + i ); } );

         std::cout << "x = " << x << std::endl;

         x = 0;

         for ( int i : v ) x = base * x + i;

         std::cout << "x = " << x << std::endl;

         return 0; 
}



You can substitute the vector for an array

int a[] = { 1, 5, 9, 3 };
In this case header <vector> shall be substituted for header <iterator> and the statement with the algorithm shall be written as

1
2
         int x = std::accumulate( begin( a ), end( a ), 0, 
                                  []( int s, int i ) { return ( s * base + i ); } );
Last edited on
@Branflakes91093
The number 1593 can be made by summing each digit multiplied by its place:
1*1000+
5*100+
9*10+
3*1=
1593


I would rewrite your expression the following way

( ( ( 0 + 1 ) * 10 + 5 ) * 10 + 9 ) * 10 + 3
closed account (Dy7SLyTq)
thanks guys this helps a lot.
@vlad: what does yours do that branflakes doesn't? i am familiar with vectors, but never read about accumulate(). also whats up with your for condition? what does the : do?
std::accumulate is a standard algorithm declared in header <numeric>. In its simple form it just summarizes all elements of a sequence in a given range.
There is a plenty of algorithms in C++. For example maybe you know already such algorithms as std::swap or std::max and std::min.
The second form I demonstrated was introduced in C++ 2011 and is known as the range-based for statement. The syntax int i : v means all elements in vector v that sequentially will be passed in variable i for processing in the body of the loop. In fact this loop is equivalent to the following

1
2
3
4
5
for ( std::vector<int>::iterator it = v.begin(); it != v.end(); ++it )
{
   int i = *it;
   // other stuff
}
Last edited on
closed account (Dy7SLyTq)
oh ok. so its kind of like a foreach loop?
@DTSCode
oh ok. so its kind of like a foreach loop?


Yes, you are right. It is the C++ syntax for the foreach loop as for example in C#.
Last edited on
closed account (Dy7SLyTq)
ok thank you
Topic archived. No new replies allowed.