[c++] How do you convert an int to an int vector
Hi!
Without using sscanf and sprintf, and using STL how do you convert:
int number=123;
to
std::vector<int> numbers;
number[0]=1;
number[1]=2;
number[2]=3;
I can do that with C functions, but no idea using STL.
Thanks a lot for your help.
You don't need C functions for this; you could do it with simple math (division and modulus) and a loop. For a hint, what's (123 % 10) and (123 / 10), in C++?
You also might want to lookup .push_back() or .resize() about vector, depending how you want to put the values into the vector, once you have them.
If you're trying to use string functions for this, as you suggested sscanf and sprintf, the normal way to do it would be with a stringstream. Put the integer in, pull the characters out.
This seems to me like the easiest way to do it:
for (;number>0; number/=10) numbers.push_back(number%10); std::reverse(numbers.begin(), numbers.end());
Quote:Original post by SiCrane
That doesn't handle zero correctly.
Indeed. Once you've written an int to string function yourself you realise that a do..while loop is most appropriate for avoiding the 0 -> "" problem.
int number = 123;std::stringstream buf;buf << number;std::string str = buf.str();
Edit: I was assuming you wanted index access to each character of the number. To actually convert to a vector would use something like alvaro's method above.
Quote:Original post by SiCrane
That doesn't handle zero correctly.
That depends on what he wants to happen when number is 0. You are probably right, though.
Quote:Original post by ricardo_ruiz_lopez
no idea using STL
Well, if it has to be STL, you can go totally berserk and write your own iterator...
#include <algorithm>#include <iostream>#include <iterator>#include <vector>class int_iterator : public std::iterator<std::forward_iterator_tag, int>{ int x;public: explicit int_iterator(int x = -1) : x(x) {} bool operator!=(int_iterator that) { return x != that.x; } int_iterator& operator++() { x /= 10; if (x == 0) x = -1; return *this; } int operator*() { return x % 10; }};int main(void){ int i = 123; std::vector<int> v((int_iterator(i)), int_iterator()); std::reverse(v.begin(), v.end());}
Note the parenthesis around int_iterator(i). Without them, you fall victim to C++'s most vexing parse.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement