简体   繁体   English

C++ - std::vector foreach - 没有重载函数的实例

[英]C++ - std::vector foreach - no instance of overloaded function

I can't figure this one;这个我想不通; I recently started to use std::for_each but this one is a pain to solve我最近开始使用std::for_each但这一个很难解决

I keep receiving an error for the code below :我不断收到以下代码的错误:

**no instance of overloaded function "std::vector<_Ty, _Alloc>::push_back [with _Ty=CharacterObject *, _Alloc=std::allocator<CharacterObject *>]" matches the argument list**

code:代码:

class Stuff
{
};  

std::vector< Stuff* > list;
list.push_back(new Stuff());
list.push_back(new Stuff());
list.push_back(new Stuff());

std::vector< Stuff* > stuffs;

std::for_each(list.begin(), list.end(), [this,level, stuff](Stuff &stuff) 
{
    ... // some conditions here
    stuffs.push_back(stuff);  << error
    stuffs.push_back(&stuff);  << also throws an error
});

I tried many different combinations, but it's hard to figure anything with STL template errors我尝试了许多不同的组合,但很难弄清楚 STL 模板错误

Any help greatly appreciated of course任何帮助当然非常感谢

sheers纯粹的

[edit: there, works like acharm and no need for bad faith I consider extremely obnoxious] [编辑:那里,像魅力一样工作,不需要恶意,我认为非常讨厌]

for (std::vector< CharacterObject* >::iterator it = spawnedCharactersObjects.begin(); it != spawnedCharactersObjects.end(); ++it)
{
    CharacterObject* characterObject = *it;
    if (characterObject->getLevel() == level)
    {
        characterObjects.push_back(characterObject);
    }
}

This is how it would be done correct这是正确完成的方式

#include <vector>
#include <algorithm>

class Stuff
{
};  

int main() {
    std::vector< Stuff* > list;
    list.push_back(new Stuff());
    list.push_back(new Stuff());
    list.push_back(new Stuff());

    std::vector< Stuff* > stuffs;

    std::for_each(list.begin(), list.end(), [&stuffs] (Stuff *stuff) {
        stuffs.push_back(stuff);
    });
    return 0;
}

std::for_each is a template function of kind std::for_each是一种模板函数

std::for_each(Container<Type>::iterator, Container<Type>::iterator, void(Type))

(That's not correct but it shows the relation between the iterator and the unary function). (这是不正确的,但它显示了迭代器和一元函数之间的关系)。 It expects as third parameter a function with one parameter of type Stuff * since list is a container containing elements of that type.它需要一个带有Stuff *类型参数的函数作为第三个参数,因为list是一个包含该类型元素的容器。 Both types have to be same.两种类型必须相同。 Also you have to capture stuffs as reference if you want to change it.如果你想改变它,你也必须捕捉stuffs作为参考。

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

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