gpt4 book ai didi

c++ - 为什么代码打印最后一个 std::cout?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:14:25 24 4
gpt4 key购买 nike

using namespace std;

template<typename T>
int f(vector<T> &v){
return v.size();
}

template<typename T>
class B{
public:
int size(){
return v.size();
};
private:
vector<T> v;
};

int main(int argc, char** argv) {

B<string> b;

vector<string> v;

for(int i=0; i<f<string>(v)-1; i++)
std::cout << "using fn template" << endl;

for(int i=0; i<b.size()-1; i++)
std::cout << "using class B" << endl;

for(int i=0; i<v.size()-1; i++)
std::cout << "done" << endl; //Why is this printing???
return (EXIT_SUCCESS);
}

最佳答案

vectorsize()函数返回 size_t 类型的值这是未签名的。所以,如果 size()返回 0 并从中减去 1,您将得到一个非常大的数字而不是 -1。这个非常大的数字将大于 0 并且条件 i < v.size() - 1因此自 i 起为真为 0。

编辑:

我应该在遍历数组或 vector 时正常添加它,只要您的索引小于数组的大小或vector,您就进行迭代而不是大小 - 1。

 for(int i = 0; i < v.size(); ++i)
std::cout << "done" << endl;

可能是您真正想做的事情。即使你使用了 (int)v.size() - 1为了摆脱签名与未签名的问题,循环仍然是错误的,因为在 vector 中确实有元素的情况下,您会错过最后一个元素。 .

关于c++ - 为什么代码打印最后一个 std::cout?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3151464/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com