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

时间:2015-07-02 23:53:34

标签: c++ vector size const unsigned-integer

我试过了:

#include <vector>

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

但得到了错误:

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'

将表达式转换为int,如下所示:

#include <vector>

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

也会产生错误:

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 '()' ?)

最后我试过了:

#include <vector>

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

给了我:

warning: implicit conversion loses integer precision

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:35)

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

#include <vector>

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

你的第三次电话

int size = v.size();

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

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

总是会干净地编译,并明确指出您要从std::vector::size_type转换为int

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