1

I'm using a library with a function that has a parameter of type int.

I need to pass the size of the vector as the argument for this parameter.

I know I can get the the size of a vector using someVector.size(), but this returns the type size_t.

I know I can cast the size_t to an int: e.g. static_cast<int>(someVector.size()). However, casting might cause problems if someVector.size() exceeds the max value of int.

What's the proper way to pass the size of a vector to a function requiring a parameter of type int?

user3731622
  • 4,844
  • 8
  • 45
  • 84

2 Answers2

2

There is no "safe" way to pass a std::size_t to a function accepting int (whenever the size_t is larger than the maximal representable int you're in trouble). You can however test if passing is safe:

if(v.size() < std::numeric_limits<int>::max()) // need to #include <limits> 
{
    // safe to pass
}
else
{
    // not safe, throw error/exit/print something
}

The comparison is always safe, provided the int is positive.

vsoftco
  • 55,410
  • 12
  • 139
  • 252
  • 1
    it probably makes sense to overload the original function with a size_t version and put this code there – user3528438 Apr 30 '15 at 01:50
  • @user3528438 not sure I understand, you mean overload the OP function that takes an `int`? – vsoftco Apr 30 '15 at 02:09
  • overload it or wrap around it – user3528438 Apr 30 '15 at 02:22
  • 1
    @user3528438 Ah ok I see. Yes, indeed, can write a wrapper or overload. The only issue may be eventual ambiguities if you pass some integral type for which the conversion to `size_t` or `int` is equally good (e.g. on my machine a `unsigned long long`). – vsoftco Apr 30 '15 at 02:38
0

I would look into the library documentation for solutions, they might accept values of type unsigned int which is pretty similar to size_t. Here is another post that might help: unsigned int vs. size_t.

Community
  • 1
  • 1
SalmonKiller
  • 2,183
  • 4
  • 27
  • 56