的向量()函数:我想初始化的for_each指针的向量的for_each指针的指针
#include <stdlib.h>
#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
class Cow{
public:
Cow(){ _age = rand()% 20; }
int get_age() { return _age;}
private:
int _age;
};
void add_new(Cow* cowp)
{
cowp = new Cow;
}
int main()
{
srand(time(NULL));
const int herd_size=10;
vector<Cow*> herd(herd_size);
for_each(herd.begin(), herd.end(),add_new);
cout << "Age: " << herd[0]->get_age() << endl; // line 27
}
不过,我在27行牛群得到一个运行“分段错误”错误矢量似乎是未初始化的。为什么?
请''设置nonu'并在注释中标注所需的行,以便我们可以复制粘贴代码并进行编译而不会混淆。 –
@jdero“add_new”是向量的每个元素上的回调函数。 – Mahesh
请不要包含行号,这会让人很难复制和粘贴。只需在评论中标注必要的行。 – BoBTFish