目前,我只能使用以下方法进行基于范围的循环:
for (auto& value : values)
Run Code Online (Sandbox Code Playgroud)
但有时我需要一个值的迭代器,而不是一个引用(无论出于何种原因).是否有任何方法无需通过整个矢量比较值?
我正在阅读Eckel的不变章节,并在Temporaries被解释的部分混淆了.我能得到的是,当我们将引用传递给函数时,编译器会创建一个临时的const对象,因此即使我们将引用作为参数传递,我们也无法修改它.
f(int &a){}
Run Code Online (Sandbox Code Playgroud)
现在我试着在网上查看其他一些Temporaries的参考资料并且被卡住了
http://publib.boulder.ibm.com/infocenter/lnxpcomp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8l.doc%2Flanguage %2Fref%2Fcplr382.htm并且
所有临时值都是用C++编写的吗?
这促使我临时工具不仅仅是传递引用并在函数内部创建const对象.现在我可以从这两个链接中获得一些东西,但不能说我已经理解了临时工作的工作,功能和用途整个.如果有人可以解释临时的概念,那将会非常有用.提前致谢.
布鲁斯·埃克尔的原始例子是:
// Result cannot be used as an lvalue
class X {
int i;
public:
X(int ii = 0);
void modify();
};
X::X(int ii) { i = ii; }
void X::modify() { i++; }
X f5() {
return X();
}
const X f6() {
return X();
}
void f7(X& x) { // Pass by non-const reference
x.modify();
}
int main() {
f5() = X(1); // OK -- non-const return value
f5().modify(); …Run Code Online (Sandbox Code Playgroud)