-1

The code

#include <iostream>
#include <vector>

int main () { std::vector<int> N = {3e6, 4e6}; }

Gives an error

error: narrowing conversion of ‘3.0e+6’ from ‘double’ to ‘int’ inside { } [-Wnarrowing]|||.

Whereas

#include <iostream>
#include <vector>

int main () {
   std::vector<int> N = {3*10^6, 4*10^6};
   for (int n: N ){ std::cout << n << std::endl; }
}

prints

24
46.

How to define this vector as an integer vector correctly?

If have found while writing this question that setting

int n1 = 3e6, n2 = 4e6;
vector<int> N = {n1, n2};

does work, but is there a better way? The type is still converted from double to int in declarations of n1 and n2.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Gytis
  • 111
  • 2
  • 5
    You do know that C++ does not have an exponentiation operator? `^` is not doing what you want it to do. –  Jun 07 '17 at 17:36
  • As the error explains, scientific notation produces `double`s. If you are sure your values are representable as `int`, you can just cast them to `int`. – François Andrieux Jun 07 '17 at 17:37
  • 1
    @NeilButterworth Yes, I know that after doing the example above. I thought that it might be useful to other noobs like me who might stumble upon this question later so wrote it up as well. – Gytis Jun 07 '17 at 18:12

1 Answers1

3

If you insist on using that notation, you can perform an explicit cast to shut the compiler up, but it's not a good idea:

#include <iostream>
#include <vector>

int main () { std::vector<int> N = {int(3e6), int(4e6)}; }
  • Can you clarify why is it not a good idea? In my view 3e6 has the advantage that it is easier to distinguish from 3e7 than distinguishing 3000000 from 30000000. Of course, 3'000'000 is the c++14 way to do it... – André Jun 07 '17 at 17:42
  • 4
    @Andre Because things like `int(3e21)` compile without warning, but almost certainly don't do what you are expecting. –  Jun 07 '17 at 17:45
  • 1
    @Andre Telling the compiler to shut up with a cast is never a good idea. It usually hides the problem but does not fix it. – Martin York Jun 07 '17 at 18:00
  • 1
    I have the same opinion as @Andre and thought that there must be a better way without getting confused by all the zeroes. – Gytis Jun 07 '17 at 18:21