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

问题描述 投票:-7回答:1

我无法想象这个;我最近开始使用std::for_each,但这个很难解决

我一直收到以下代码的错误:

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

码:

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
});

我尝试了很多不同的组合,但很难用STL模板错误来计算任何东西

任何帮助当然非常感谢

透明薄纱

[编辑:在那里,工作像acharm,不需要恶意,我认为非常讨厌]

for (std::vector< CharacterObject* >::iterator it = spawnedCharactersObjects.begin(); it != spawnedCharactersObjects.end(); ++it)
{
    CharacterObject* characterObject = *it;
    if (characterObject->getLevel() == level)
    {
        characterObjects.push_back(characterObject);
    }
}
c++ foreach stl
1个回答
1
投票

这就是如何正确完成的

#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是一种模板功能

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

(这不正确,但它显示了迭代器和一元函数之间的关系)。它期望第三个参数是一个具有Stuff *类型参数的函数,因为list是一个包含该类型元素的容器。两种类型都必须相同。如果你想改变它,你还必须捕获stuffs作为参考。

© www.soinside.com 2019 - 2024. All rights reserved.