0

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];
Allen Huang
  • 394
  • 2
  • 14
  • I question why you need to do this. Also why not convert it to `std::string`? – NathanOliver May 27 '16 at 13:32
  • You can use `itoa` to go from int to char like you want. std::transform (http://www.cplusplus.com/reference/algorithm/transform/) will let you do it on a container. –  May 27 '16 at 13:34
  • What result do you expect for integers larger than 9, or smaller than 0? – IInspectable May 27 '16 at 13:38

5 Answers5

5

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).

Quentin
  • 62,093
  • 7
  • 131
  • 191
  • Is there a way to do this so that the char array is dynamically allocated? so it can have variable size – Allen Huang May 27 '16 at 14:08
  • @AllenHuang You could allocate it with `new` and pass the pointer itself to `std::transform`, but the better idea is to use `std::vector`. – Quentin May 27 '16 at 14:15
  • that worked thanks and I am using a char array because I'm using this with zLib – Allen Huang May 27 '16 at 14:17
2

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.

Slava
  • 43,454
  • 1
  • 47
  • 90
0

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

Community
  • 1
  • 1
RvdK
  • 19,580
  • 4
  • 64
  • 107
0

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);
}
Sean
  • 60,939
  • 11
  • 97
  • 136
0

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;
}
Mayhem
  • 487
  • 2
  • 5
  • 13