为什么在调用此列表时需要"&"?
Why "&" is needed during calling this list?
我在学习list并玩函数,这个程序会给出10个数字,每次如果输入的数字大于我们列表中的最大值,这个数字就会被添加到我们的列表中,最后在10次尝试后,所有成员都会出现。该程序运行良好,但我不明白的是,为什么我需要在第6行使用"&":"void insertMax(list&lst,int n){"??
#include <iostream>
#include <list>
using namespace std;
void insertMax(list<int> &lst, int n) {
lst.sort();
int max = lst.back();
if (n > max) {
lst.push_back(n);
}
}
void disply(list<int> lst) {
list<int>::iterator iter = lst.begin();
while (iter!=lst.end()){
cout << *iter << endl;
iter++;
}
}
int main()
{
list<int> numbers;
numbers.push_back(0);
int input=0;
for (int j = 1; j < 11; j++){
cout << "Enter a number: " << endl;
cin >> input;
insertMax(numbers, input);
}
cout << "Now that's all: " << endl;
disply(numbers);
return 0;
}
提前谢谢。
因此,您可以传递对列表的引用,而不是它的副本。
谷歌"按引用传递"answers"按值传递"。
通过引用意味着你不必复制你正在传递的整个数据结构(这可能很慢,尤其是如果你有一个大列表)
话虽如此,您的问题还不太清楚:"为什么在调用这个列表时需要&?"-第6行不是调用,而是函数签名的声明。所以它说"当你打电话给我时,我希望你传递一个对int列表的引用"
通过将"与"号(&)放入,可以指定将列表作为引用,而不是复制到函数范围中。通过将其作为引用,可以操纵外部对象。http://www.cprogramming.com/tutorial/references.html
如果我理解正确,第6行是函数定义的起始行
void insertMax(list<int> &lst, int n) {
lst.sort();
int max = lst.back();
if (n > max) {
lst.push_back(n);
}
}
第一个参数声明中的符号&
表示该参数将引用原始参数。因此,函数中列表的任何更改都会影响原始参数。
如果要删除此符号&
,例如
void insertMax(list<int> lst, int n) {
//...
it将意味着该函数将处理原始参数的副本。在这种情况下,参数副本中的参数的任何更改都不会影响原始参数。
因此,新项目将添加到列表的副本中,但列表本身不会更改。它的副本将被更改。
如果不添加'&'(通过引用传递),在InsertMax函数中对List所做的任何更改都不会影响主方法中的列表。
这就是为什么您有时会看到C++方法签名声明为的原因
void DoSomething(const std::string &value)
{
/*Method Body*/
}
这样做是为了不将value
字符串中的所有数据复制到内存中的新位置。如果DoSomething
方法需要修改值字符串,则需要首先在函数内部复制它。const
修饰符确保该方法的引用是只读的。
例如:
std::string DoSomething(const std::string &value)
{
std:string result = value + "some other data";
return result;
}
- 没有为自己的结构调用列表推回方法
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 如何在C++中调用列表中的某个值
- 调用重载的"<大括号括起来的初始值设定项列表>"对于对来说就足够了是模棱两可的
- 在初始化列表之外手动调用基类的构造函数
- C++:带有大括号初始化列表的函数调用表达式 - 标准是否规定在单个元素列表的微不足道的情况下忽略大括号?
- C++如果两个模板函数都与参数列表匹配,将调用哪个模板
- 如何获取列表的每个对象并调用getName方法来打印其名称
- 如何在构造器的成员初始值设定项列表中调用两个函数?
- 使用显式模板参数列表和 [temp.arg.explicit]/3 的函数调用的演绎失败
- 使用成员初始值设定项列表时没有匹配的函数调用错误
- 将值推送到 getter 函数调用的列表中时出现问题
- C++:如何在对象构造过程中调用初始值设定项列表之外的成员构造函数
- 如何在C++中泛化调用函数列表?
- 构造函数初始值设定项列表未调用复制构造函数
- 如何从LLVM的中间表示中获取在程序的每个函数中执行的函数调用列表
- 调用列表中子对象方法的最佳方法
- 如何最小化调用列表构造函数(复制构造函数)的次数?
- 调用列表中的子对象
- 如何调用列表中对象的函数