C++ - Return 对向量元素的引用

C++ - Return reference to a vector element

我想 return 对向量中单个元素的引用作为参数获取,然后比较那里的内存地址。我的代码的一个简化示例如下所示:

const int &test(std::vector<int> i) {
    return i.at(3);
}

TEST(test, all_test) {
    const std::vector<int> i = {1,2,3,4,5};
    const int &j = test(i);
    ASSERT_THAT(&j, Eq(&i.at(3)));
}

使用这个我得到以下错误信息:

Failure
Value of: &j
Expected: is equal to 0x55da7899d4dc
  Actual: 0x55da7899d4fc (of type int const*)

如何return引用单个矢量元素?

您按值传递矢量,因此返回对临时元素的引用。如果你通过引用传递向量,你应该没问题。