7

If a user enters an integer like 4210 for example, how can I put each digit of that integer in a vector in C++?

Adrian W
  • 4,563
  • 11
  • 38
  • 52
Mohamed Ahmed
  • 457
  • 1
  • 7
  • 25

4 Answers4

10

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());
Nejat
  • 31,784
  • 12
  • 106
  • 138
  • Well, I will try it. It doesn't matter - for my application - if the addition was in reverse order. – Mohamed Ahmed Apr 02 '14 at 17:35
  • 1
    change it to a stack, or treat the vector like a stack..."reverse order" is relative to how you read it later. – Red Alert Apr 02 '14 at 17:36
  • use 'numbers.emplace(numbers.begin(), x%10);' instead of 'push_back()' to avoid overhead of reversing the vector. – dixit_chandra May 22 '21 at 08:39
  • Using `emplace(begin())` does not improve performance, but instead makes performance worse, because each `emplace` at the beginning requires all previously added elements to be moved, giving the entire loop complexity O(n^2), whereas `std::reverse` has complexity O(1). – Florian Winter May 25 '21 at 10:27
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;
    }
Anant Jain
  • 21
  • 2
1

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');
}
Matthieu M.
  • 287,565
  • 48
  • 449
  • 722
0

Or if you prefer using std::string you can use:

std::vector<int> intVector;

int x;
std::cin >> x;

for (const auto digit : std::to_string(x)) {
    intVector.push_back(digit - '0');
}

This assumes your compiler can use C++11.

Live example

Floris Velleman
  • 4,848
  • 4
  • 29
  • 46
  • My compiler is gcc on Ubuntu Linux, it is updated to version 4.8.1. I normally compile my simple programs with 'g++ -Wall -o'. How to compile on C++ if that wasn't it? – Mohamed Ahmed Apr 02 '14 at 17:41
  • 1
    @MohamedAhmed g++ -std=c++11 -Wall -o, should work fine. – Floris Velleman Apr 02 '14 at 17:42
  • Those 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. – Mohamed Ahmed Apr 02 '14 at 17:45