繁体   English   中英

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

[英]How can I get the size of an std::vector as an int?

我试过了:

#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

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

在前两种情况下,你只是忘了实际调用成员函数(!,它不是一个值) 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_typeint是有意的。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM