C++ 如何将 std::vector 的大小作为 int 获取?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31196443/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the size of an std::vector as an int?
提问by Flashpaper
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 intlike this:
将表达式转换为int如下所示:
#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?
我怎样才能解决这个问题?
回答by Baum mit Augen
In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::sizelike this:
在前两种情况下,您只是忘记实际调用成员函数(!,它不是值),std::vector<int>::size如下所示:
#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.
触发警告,因为并非该函数的每个返回值(通常是 64 位无符号整数)都可以表示为 32 位有符号整数。
int size = static_cast<int>(v.size());
would always compile cleanly and also explicitly states that your conversion from std::vector::size_typeto intwas intended.
将始终干净地编译,并且还明确指出您从std::vector::size_typeto的转换int是有意的。
Note that if the size of the vectoris greater than the biggest number an intcan represent, sizewill contain an implementation defined (de facto garbage) value.
请注意,如果 的大小vector大于int可以表示的最大数字,size则将包含实现定义的(事实上的垃圾)值。

