我想在 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 行收到运行时“分段错误”错误。群体向量似乎未初始化。为什么?