54

I tried:

#include <vector>

int main () {
    std::vector<int> v;
    int size = v.size;
}

but got the error:

cannot convert 'std::vector<int>::size' from type 'std::vector<int>::size_type (std::vector<int>::)() const noexcept' {aka 'long unsigned int (std::vector<int>::)() const noexcept'} to type 'int'

Casting the expression to int like this:

#include <vector>

int main () {
    std::vector<int> v;
    int size = (int)v.size;
}

also yields an error:

error: invalid use of member function 'std::vector<_Tp, _Alloc>::size_type std::vector<_Tp, _Alloc>::size() const [with _Tp = int; _Alloc = std::allocator<int>; std::vector<_Tp, _Alloc>::size_type = long unsigned int]' (did you forget the '()' ?)

Last I tried:

#include <vector>

int main () {
    std::vector<int> v;
    int size = v.size();
}

which gave me:

warning: implicit conversion loses integer precision

How can I fix this?

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
Flashpaper
  • 571
  • 1
  • 5
  • 5
  • 2
    You can use `std::size(v);` it is introduced with c++17 – anilbey Jul 17 '18 at 20:05
  • @anilbey You probably mean `std::ssize(v);` that is introduced with C++20 because `std::size` doesn't fix the last problem. – L. F. Jul 12 '19 at 06:13
  • @L.F. could you briefly explain the difference between those two? – anilbey Jul 14 '19 at 11:08
  • @anilbey `std::size` returns an unsigned integer, `std::ssize` returns a signed integer. Except I just noticed that `ssize` doesn't solve the problem either ... – L. F. Jul 14 '19 at 11:09

2 Answers2

77

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

Baum mit Augen
  • 49,044
  • 25
  • 144
  • 182
0

Easy :) Use the following code instead of your code.

auto size = v.size();
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 24 '23 at 17:39