c++ - 为什么我的列表值被覆盖?

标签 c++ arrays list

我目前已经创建了一个小程序来学习列表。我允许用户将随机整数添加到列表中。只需使用 DList.insert(number, position) 即可很好地添加它们。第一次迭代一切正常,但当我允许用户输入更多随机数时,它会删除之前的数字,然后添加更多随机数。

由于我是 C++ 的新手(很少用它来编程),所以我认为我犯了一个非常简单的错误。问题似乎是我只是覆盖列表中的旧值而不是添加新值。

这是我正在做的,

List testList;
//Ask user for a number of elements to add
int num = get_number();
addRandInts(testList, num);
//I then give the user the option to add more or quit

这是我的addRandInts:

void addRandInts(List dl, int num) 
{
    int random_max = 999;
    int numIterations = dl.getSize() + num;

    if(num > 0) {
        cout << "Array Size: " << dl.getSize() << endl;
        for(int i = dl.getSize(); i < numIterations; i++) {
            dl.insert(rand() % random_max + 1, i); 
        }
    } else {
        cout << "You need to enter a positive integer" << endl;
    }
    dl.display(cout);
 }

如果需要,我可以提供我的 List.insert(List, pos) 方法。

这是示例输出:

Please enter an integer number for the list: 5
Current Size: 0
42  486  341  527  189

//chance to add more to list
Please enter an integer number for the list: 3
Current Size: 0
740  490  388

所以在第二次运行时,我想我应该有 5 的大小,并且应该向它添加 3。 由于我不熟悉指针等,我应该将指针传递给列表而不是列表吗?

最佳答案

您正在按值将列表传递给 addRantInts() 函数,这意味着该函数正在修改列表的拷贝而不是原始列表。为避免这种情况,请改为通过引用传递它:

void addRandInts(List & dl, int num)    // <-- note ampersand!

关于c++ - 为什么我的列表值被覆盖?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19484687/

相关文章:

c++ - 此像素着色器中的漫反射和镜面反射

c++ - 如何理解*(void **)(&m_handle)= dlsym (“./haldle_lib.so”, “custom_func”);

c - 了解 C 中的数组指针初始化语法

python - 使用任意长度索引设置嵌套列表中的元素

c++ - vector 的初始化 vector

c++ - 模板模板参数什么时候成为标准的一部分?

javascript - 带有标题和子标题的代码

javascript - 在javascript中的字典(关联数组)中使用变量

Python - 实例变量列表的最小值

r - 跨字符串向量迭代单词并将更改应用于单个单词