How to put digits of an integer in a vector in C++
11,337
Solution 1
It can be done like:
std::vector<int> numbers;
int x;
std::cin >> x;
while(x>0)
{
numbers.push_back(x%10);
x/=10;
}
std::reverse(numbers.begin(), numbers.end());
Solution 2
The Easiest way I found is this :
std::vector<int> res;
int c;
std::cin >> c;
while(c>0)
{
res.insert(res.begin(),c%10);
c/=10;
}
Solution 3
I don't understand why people advise such round about solutions as converting back and forth to int
when all you want is digit by digit... for a number expressed in decimal by the user.
To transform "4321"
into std::vector<int>{4, 3, 2, 1}
the easiest way would be:
std::string input;
std::cin >> input;
std::vector<int> vec;
for (char const c: input) {
assert(c >= '0' and c <= '9' and "Non-digit character!");
vec.push_back(c - '0');
}
Related videos on Youtube
Author by
Mohamed Ahmed
Embedded Software Engineer. Skilled in C and Python.
Updated on June 04, 2022Comments
-
Mohamed Ahmed about 2 years
If a user enters an integer like 4210 for example, how can I put each digit of that integer in a vector in C++?
-
berkus about 10 yearsSimplest would be to input it as a string and then just iterate that string, pushing every element into a vector. After you have each digit separately it's trivial to lexically cast it to integer for vector<int>.
-
-
Mohamed Ahmed about 10 yearsWell, I will try it. It doesn't matter - for my application - if the addition was in reverse order.
-
Red Alert about 10 yearschange it to a stack, or treat the vector like a stack..."reverse order" is relative to how you read it later.
-
Floris Velleman about 10 years@MohamedAhmed g++ -std=c++11 -Wall -o, should work fine.
-
Mohamed Ahmed about 10 yearsThose numbers represent the powers in an equation of the taps in a linear feedback shift register, I will use the numbers as addresses for bits to be xored in a bitset. So, I don't think that conversion into a string is correct if I want to do that, I just want them integers as they are. Thank you.
-
dixit_chandra about 3 yearsuse 'numbers.emplace(numbers.begin(), x%10);' instead of 'push_back()' to avoid overhead of reversing the vector.
-
Florian Winter about 3 yearsUsing
emplace(begin())
does not improve performance, but instead makes performance worse, because eachemplace
at the beginning requires all previously added elements to be moved, giving the entire loop complexity O(n^2), whereasstd::reverse
has complexity O(1).