如何将std :: vector的大小作为int?

Fla*_*per 33 c++ size const vector unsigned-integer

我试过了:

#include <vector>

int main () {
    std::vector<int> v;
    int size = v.size;
}
Run Code Online (Sandbox Code Playgroud)

但得到了错误:

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'
Run Code Online (Sandbox Code Playgroud)

将表达式转换为int如下:

#include <vector>

int main () {
    std::vector<int> v;
    int size = (int)v.size;
}
Run Code Online (Sandbox Code Playgroud)

也会产生错误:

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 '()' ?)
Run Code Online (Sandbox Code Playgroud)

最后我试过:

#include <vector>

int main () {
    std::vector<int> v;
    int size = v.size();
}
Run Code Online (Sandbox Code Playgroud)

这给了我:

warning: implicit conversion loses integer precision
Run Code Online (Sandbox Code Playgroud)

我怎样才能解决这个问题?

Bau*_*gen 41

在前两种情况下,你只是忘了实际调用成员函数(!,它不是一个值),std::vector<int>::size如下所示:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}
Run Code Online (Sandbox Code Playgroud)

你的第三个电话

int size = v.size();
Run Code Online (Sandbox Code Playgroud)

触发警告,因为并非该函数的每个返回值(通常是64位无符号整数)都可以表示为32位有符号整数.

int size = static_cast<int>(v.size());
Run Code Online (Sandbox Code Playgroud)

总是会顺利地编译和还明确规定,从转换std::vector::size_typeint之意.

请注意,如果大小vector大于int可以表示的最大数字,size则将包含实现定义(事实上的垃圾)值.