为什么在调用此列表时需要"&"?

Why "&" is needed during calling this list?

本文关键字:调用 列表 为什么      更新时间:2023-10-16

我在学习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;
}