向量大小 - 在 C++ 中大小为 0 时为 1

2021-12-21 00:00:00 size vector c++

以下代码

#include <vector>
#include <iostream>
using namespace std;
int main() {
    vector<int> value;
    cout << value.size() << endl;  // output 0
    cout << value.size() - 1 << endl;  // output 18446744073709551615
}

为什么第二个输出不是-1?第二次 cout 会发生什么?

Why the second output is not -1? What happens at the second cout?

推荐答案

vector::size()size_t 类型,它是无符号类型和无符号整数不能表示负数.

vector::size() is of type size_t which is an unsigned type, and unsigned integers can't represent negative numbers.

相关文章