我似乎无法使用std :: find来使用std ::对象列表。我得到了错误" 与'operator =='不匹配(操作数类型是'Rabbit'和'const int')"。相当确定我需要使用对象迭代器和lambda函数,我完全不知道如何这样做,我只需要一些指导。我最终要做的是迭代到列表中的特定位置,并从列表中的该对象中拉出颜色字符串。 编辑澄清问题并简化代码
#include <iostream>
#include <list>
#include <algorithm>
#include "Rabbit.h"
#include "Population.h"
using namespace std;
int main()
{
Population Tracker;
Tracker.parentSeed(); //generate first random 8, and populate the list
Tracker.Breed(); //generate children, not working nothing happening as getMother does not work
return 0;
}
class Rabbit
{
protected:
const std::vector<std::string> namesList
{"Maxwell", "David", "Laura", "Sarah" , "Benjamin", "Carl",
"Rick", "Maggie", "Glenn", "Daryl", "Michonne", "Roseita",
"Leslie", "Randy", "Ethan", "Survan", "Leah", "Tisha", "Marcus"};
const std::vector<std::string> colorList
{"Red", "Green", "Blue",
"Grey", "Tan", "Brown",
"Calico", "White"};
public:
Rabbit(); //blank for the initial population
Rabbit(int); // pass an int for color inherited from mother
~Rabbit();
void getRabbit();
void randomNumGen(int);
std::string name;
std::string color;
};
Rabbit::Rabbit()
{
std::random_device random; //random seed obj
std::default_random_engine e1(random()); //get a random number seed
std::uniform_int_distribution<int> name_dist(0, 17); // vector position of name
std::uniform_int_distribution<int> color_dist(0, 7); // vector position of col
color = colorList[color_dist(e1)];
name = nameList[name_dist(e1)];
}
class Population
{
friend class Rabbbit;
protected:
public:
Population();
void popStats(int, bool);
void popList(Rabbit);
int getMother();
void parentSeed(); // generate initial population. All stats are random.
std::list<Rabbit> femaleList;
std::list<Rabbit> maleList;
std::list<Rabbit>::iterator male_it;
std::list<Rabbit>::iterator female_it;
};
int Population::getMother()
{
female_it++
//do something to iterate list and get data from the object at that position. Not to be sequential, just used that as example.
}
void Population::Breed()
{
/*
generate a new rabbit with color inhereited from the mother
father does not matter as all other stats are random
*/
if(maleList.size() > 2 && femaleList.size() > 2)
{
getMother(); // does nothing right now
std::cout << "Breed Success!" << std::endl;
Rabbit newRabbit;
popList(newRabbit);
}
}
void Population::parentSeed()
{
/*
Generate the initial seed count
*/
for (int i = 0; i < 8; i++)
{
Rabbit newRabbit;
popList(newRabbit);
}
}
答案 0 :(得分:0)
编译器不知道如何区分Rabbit
和原始整数。因此,它告诉您需要通过为Rabbit
对象和整数定义重载的等于运算符来向它展示如何区分它们。您应该将以下重载的运算符添加到您的代码中:
bool
operator==(int const &i, Rabbit const &r) {
...
return ?;
}
bool
operator==(Rabbit const &r, int const &i) {
...
return ?;
}