How to turn a vector into a value?

Lets say I have a vector with five entries [1,2,3,4,5]. How do I convert this into the value 12345 so I can set it equal to a variable?

Last edited on
EDIT: The following will work for a vector containing only single-digit elements. You can modify the algorithm to work for any number of digits yourself.

You need an algorithm that describes how to go from 1->12 and 12->123 and so on.

The pattern is that each previous number is multiplied by 10, and the current value is then added to it. The value we start with is actually 0.

For example:
To get to 1: 0*10 +1
To go from 1 to 12: 1*10 + 2
To go from 12 to 123: 12*10 + 3
and so on...

Can you translate this logic to c++?
Last edited on
You could use a stringstream.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
#include <sstream>
#include <vector>
using namespace std;

int main()
{
    vector<int> v = {1, 2, 3, 4, 5};

    stringstream ss;
    for(auto e : v)
        ss << e;

    int num;
    ss >> num;
    cout << num << '\n';
}

I'm tempted to say that this only needs the logic to be filled in:
1
2
3
auto result = std::accumulate( std::begin(numbers),
                               std::end(numbers), 0LL,
                               [](int x, int y){return /*logic*/;} );

However, one has to read and understand the descriptions of its constructs before the "black box" becomes useful.

Furthermore, there are considerations. Multi-digit values, negative values, total of too many digits to fit into the integral output type, etc.
Topic archived. No new replies allowed.