c++ - 如何使用const_reference类型声明变量并赋值给它,即front()函数的返回值

标签 c++ vector stl

我声明了一个 vector 并用三个值初始化它,

vector<int> vec{1, 2, 3};

我尝试将 vec.front() 的返回值分配给引用变量 a

如何声明使用正确的数据类型?

我试过了,

vector<int>::const_reference &a = vec.front();           

但是这句话是什么意思呢?

我可以先使用正确的数据类型声明变量 a 然后使用

a = vec.front();

将 vec.front() 的返回值赋给变量 a?如果是的话我应该写什么?

最佳答案

Can I first declare the variable a using proper data type and then use

a = vec.front();

to assign the returned value of vec.front() to the variable a

a不是普通变量;它是一个引用,声明引用而不说明它所指的内容是不合法的:

const int& a;  // Illegal

声明引用后,对该变量执行的所有操作实际上都是对其引用的值执行,因此您永远无法更改引用引用的内容。

const int& a = b;
a = 10;  // Changed the value of b.

I tried, vector<int>::const_reference &a = vec.front();

这似乎是一种过于冗长的说法:

const int& a = vec.front();

vec.front()返回对 vector 前面元素的引用。 const int& a = vec.front()声明变量a这样它就是对 vector 前面元素的引用。

通过 promise 只读该值来避免复制。

如果你说:

int a = vec.front();

a现在将是数组第一个元素的拷贝,但您可以随意更改它。

对于 int 来说,没有性能优势。但是如果你的 vector 是 string 的 vector s,获取引用将避免复制字符串,如果您不打算修改内容,这可能比引用具有显着的性能优势。

std::string str = "hello world, this is a long string.";
const std::string& a = str;  // Reference, no copy
std::string b = str;  // Copy of str, takes extra effort

关于c++ - 如何使用const_reference类型声明变量并赋值给它,即front()函数的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36815724/

相关文章:

c++ - 尽可能小地从 Boost 中提取 sublib

c++ - 如何获得 std::map 的真正分配器?

c++ - 从对象成员传递 const 引用。即 someObject.function()

c++ - STL 删除没有按预期工作?

c++ - 使用 std::vector 时处理内存

c++ - std::vector<T>::iterator 可以只是 T* 吗?

vector - 两个3D向量之间的X角?

c++ - 附加到具有非动态分配堆栈的 vector

c++ - 为什么 gdb 不能附加到由 inetd 调用的服务器应用程序?

c++ - 如何比较两个 HANDLE 类型的变量