如何获取std :: vector的大小作为int? [英] How can I get the size of an std::vector as an int?

查看:409
本文介绍了如何获取std :: vector的大小作为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

Casting the expression to int like this:

#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

如何我解决了这个问题吗?

How can I fix this?

推荐答案

在前两种情况下,您只是忘记了实际调用成员函数(!值) std :: vector< int> :: size 像这样:

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();
}

您的第三次通话

int size = v.size();

触发警告,因为并非该函数的每个返回值(通常为64位unsigned int)都可以

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());

将始终干净地编译,并且还明确指出您从 std ::进行的转换:将vector :: size_type 转换为 int

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.

这篇关于如何获取std :: vector的大小作为int?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆