Allen Huang
Allen Huang

Reputation: 394

Converting from a std::vector<int> to a char[] C++

If I have an integer vector (std::vector) is there an easy way to convert everything in that vector to a char array(char[]) so (1,2,3) -> ('1','2','3') This is what I have tried, but it doesn't work:

std::vector<int> v;

for(int i = 1; i  < 10; i++){
    v.push_back(i);
}

char *a = &v[0];

Upvotes: 0

Views: 7384

Answers (5)

Sean
Sean

Reputation: 62532

If you've already got the numbers in a vector then you can use std::transform and a back_inserter:

std::vector<int> v;

std::vector<char> c;
std::transform(v.begin(), v.end(), std::back_inserter(c), [](int i){return '0' + i;});

However, why not just say:

std::vector<char> v;

for(char i = '0'; i < '9'; i++)
{
    v.push_back(i);
}

Upvotes: 0

Mayhem
Mayhem

Reputation: 507

You can use std::transform with std::back_inserter, maybe something like this:

#include <iostream>
#include <vector>
#include <algorithm>

int main()
{
    std::vector<int> vI{0,1,2,3,4,5,6,7,8,9};
    std::vector<char> vC;
    std::transform(vI.begin(), vI.end(), std::back_inserter(vC), [](const int &i){ return '0'+i; });

    for(const auto &i: vC)
    {
        std::cout << i << std::endl;
    }
    return 0;
}

Upvotes: 0

Quentin
Quentin

Reputation: 63154

std::transform is the right tool for the job :

std::vector<int> iv {1, 2, 3, 4, 5, 6};
char ca[10] {};

using std::begin;
using std::end;
std::transform(begin(iv), end(iv), begin(ca), [](int i) { return '0' + i; });

If you don't need ca to be a C-style array, I'd recommend using std::array or std::vector instead. The latter needs std::back_inserter(ca) in place of begin(ca).

Upvotes: 5

RvdK
RvdK

Reputation: 19800

Why not store it in char vector initially?

std::vector<char> v;
for(int i = 1; i  < 10; i++){
    v.push_back(i + '0');
}

Trick from: https://stackoverflow.com/a/2279401/47351

Upvotes: 0

Slava
Slava

Reputation: 44268

It can be as simple as this

std::vector<int> v { 1, 2, 3 };
std::vector<char> c;
for( int i : v ) c.push_back( '0' + i );

to realize why your way does not work you need to learn how integers and symbls represented on your platform.

Upvotes: 2

Related Questions