sizeof(vector) 的大小是多少?C++

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

因此用户在 for 循环中输入值,向量将其推回,创建自己的索引.问题出现在第二个 for 循环中,我认为它必须对 sizeof(v)/sizeof(vector) 做一些事情.

So the user inputs values within the for loop and the vector pushes it back, creating its own index. The problem arises in the second for loop, I think it has to do something with sizeof(v)/sizeof(vector).

 vector<int> v;

 for (int i; cin >> i;)
 {
    v.push_back(i);
    cout << v.size() << endl;
 }

 for (int i =0; i < sizeof(v)/sizeof(vector); i++)
 {
    cout << v[i] << endl;
 }

输入值后如何确定向量的大小?(我对 C++ 很陌生,所以如果我犯了一个愚蠢的错误,我道歉)

How will I determine the size of the vector after entering values? (I'm quite new to C++ so If I have made a stupid mistake, I apologize)

推荐答案

使用 vector::size() 方法:i

v.size().

sizeof 运算符返回编译时对象或表达式的大小(以字节为单位),对于 std::vector 来说是常量.

The sizeof operator returns the size in bytes of the object or expression at compile time, which is constant for a std::vector.

相关文章