Take element size from a vector?

Asked

Viewed 58 times

2

I have a vector like this: int nums[10] + {1235, 14627, 1625161, 54437};

Always the element will be greater than or equal to 1000, that is, with length equal to 4, and can extend up to 10 digits. I want to know how I get the length of these integers from my vector. That is, using the example vector, I have the first element that has 4, others with 5, 7 and 5 respectively. But how do I get the length by the code?

  • I voted as a duplicate because the two questions are closely related - you can’t answer the other one without answering that one as well. Also, by "element size" you mean "number of decimal digits". You could define "size" in other ways as well (in memory, all elements have the same size - they are 32-bit integers).

1 answer

4


So suddenly I see two ways: converting to string or using the function log().

#include <string.h> // para strlen()

int nums[] = {1235, 14627, 1625161, 54437};
for (int k = 0; k < sizeof nums / sizeof *nums; k++) {
    char tmp[12];
    sprintf(tmp, "%d", nums[k]);
    printf("O numero %d tem comprimento %d.\n", nums[k], (int)strlen(tmp));
}

or

#include <math.h> // para log()

int nums[] = {1235, 14627, 1625161, 54437};
for (int k = 0; k < sizeof nums / sizeof *nums; k++) {
    printf("O numero %d tem comprimento %d.\n", nums[k], (int)log10(nums[k]) + 1);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.