简体   繁体   English

无法插入std :: list吗?

[英]Can't insert into std::list?

I'm trying to insert values into a std::list called in a void. 我正在尝试将值插入到在void中调用的std :: list中。 The void will insert values into the list to be used when it's called from another function, but when I try to insert values into the list with .push_back , .Insert or .Add, I get the following error: 从另一个函数调用时,void将值插入要使用的列表中,但是当我尝试使用.push_back,.Insert或.Add将值插入到列表中时,出现以下错误: 我收到以下错误

Here's my code: 这是我的代码:

void pb(std::list<unsigned long long int> primeFactorisation(unsigned long long int), int n)
{
    for (int i=n; i<n; i++)
    {
        primeFactorisation.push_back(i);
    }
}

I don't understand what I'm doing wrong, this is a standard list? 我不明白自己在做什么错,这是标准清单吗?

In

void pb(std::list<unsigned long long int> primeFactorisation(unsigned long long int), int n)

your first parameter 您的第一个参数

std::list<unsigned long long int> primeFactorisation(unsigned long long int)

declares a function, not a std::list parameter. 声明一个函数,而不是一个std::list参数。 You need 你需要

void pb(std::list<unsigned long long int>& primeFactorisation, int n)

for pb to work correctly (note that primeFactorisation needs to be passed by reference for it to modify the list passed from the call site). 为了使pb正常工作(请注意primeFactorisation需要通过引用传递,以修改从呼叫站点传递的列表)。


You also have an issue with your for loop. 您的for循环也有问题。

for (int i=n; i<n; i++)

will never run as i == n in the first loop so i < n will be false before you even start. 永远不会在第一个循环中以i == n运行,所以i < n在开始之前就为false

Try: 尝试:

void pb(std::list<unsigned long long int>& primeFactorisation, int n)
{
    for (int i=0; i<n; i++)
    {
        primeFactorisation.push_back(i);
    }
}

Your initial version is almost formatted to accept a function called primeFactorisation due to the inclusion of (unsigned long long int) . 由于包含(unsigned long long int)您的初始版本几乎被格式化为接受称为primeFactorisation的函数。

As @FrançoisAndrieux points out, the list needs to be passed by reference or pointer, or a temporary copy will be made and none of your push_back() s will affect the original list passed by the caller. 正如@FrançoisAndrieux指出的那样,该列表需要通过引用或指针传递,否则将创建一个临时副本,并且您的push_back()都不会影响调用者传递的原始列表。

Also, you're starting your for loop at a point where it will never execute. 另外,您将在永远不会执行的位置开始for循环。

for(int i=n;i<n;i++)

Could be rephrased as: 可以改写为:

i=n;  // ok
is i < n? // nope, since you just set i=n.

Instead, set i=0 in the first part of the for . 而是在for的第一部分中设置i=0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM