我尝试过:
#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::size(v);
,它是在c++17中引入的。 - anilbeystd::ssize(v);
,它是在 C++20 中引入的,因为std::size
没有解决最后一个问题。 - L. F.std::size
返回一个无符号整数,std::ssize
返回一个有符号整数。但我刚注意到ssize
也无法解决这个问题... - L. F.