因此,我试图在 codegolf 上的 C++ 中何时为 x==x+2提出一个解决方案,并提出这个片段只是为了意识到我不知道它是如何工作的。我不确定为什么这两个条件都评估为真。
有谁知道标记line:
为真的行是因为 x==&x 还是因为 x+2 在 == 的左侧之前被评估?
#include <iostream>
#include <vector>
std::vector<int>& operator+ ( std::vector<int> &v, int val )
{
v.push_back(val);
return v;
}
int main()
{
std::vector<int> x;
std::vector<int> y = x + 2; // y is a copy of x, and x is [2]
// how are both of these are true?
std::cout << (x==y) << "\n"; // value comparison [2]==[2]
line:
std::cout << (x==x+2) << "\n"; // reference comparison? &x == &(x+2)
// not sure if this is relevant
std::cout << (x+2==x) << "\n"; // also true
return 0;
}
似乎——因为向量似乎是按值比较的——如果 x 在 x+2 之前被评估,那么 x 将不等于 x+2(按值)。我可能遗漏了一些明显的东西。提前致谢。