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?
#include <iostream>
#include <vector>
#include <numeric>
int main()
{
std::vector<int> v = { 1, 5, 9, 3 };
constint 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 ); } );
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
}