gpt4 book ai didi

c++ - 从 vector 中删除一个元素

转载 作者:行者123 更新时间:2023-11-28 05:14:44 26 4
gpt4 key购买 nike

我是 C++ 的新手,我正在编写一个程序来模拟一群兔子。该程序将能够添加它们,给它们命名、年龄、颜色等。现在我有一个工作程序,它会在每次通过后添加兔子并将它们的年龄增加 1。一旦兔子到了 10 岁。

代码:

enter code here
#include <iostream>
#include <ctime>
#include <vector>
#include <cstdlib>
#include <limits>

using namespace std;

const int POSSIBLE_NAMES = 18;
const int POSSIBLE_COLORS = 4;

static std::string possibleNames[] ={
"Jen",
"Alex",
"Janice",
"Tom",
"Bob",
"Cassie",
"Louis",
"Frank",
"Bugs",
"Daffy",
"Mickey",
"Minnie",
"Pluto",
"Venus",
"Topanga",
"Corey",
"Francis",
"London",
};
static std::string possibleColors[] ={

"White",
"Brown",
"Black",
"Spotted"
};

struct Bunny
{
public:

string name;
int age;
string color;
char sex;

Bunny(){
setSex();
setColor();
setAge(0);
setName();
}

int randomGeneration(int x){
return rand() % x;
srand (time(NULL));
}

void setSex()
{
int randomNumber = randomGeneration(2);
( randomNumber == 1 ) ? sex = 'm' : sex = 'f';
}

char getSex()
{
return sex;
}

void setColor()
{
int randomNumber = randomGeneration(POSSIBLE_COLORS);
color = possibleColors[randomNumber];
}

string getColor()
{
return color;
}

void setAge(int age)
{
this->age = age;
}

int getAge()
{
age++;
return age;
}

void setName()
{
int i = randomGeneration(POSSIBLE_NAMES);
name = possibleNames[i];
}

string getName()
{
return name;
}

void deleteBunny(){
if (age > 10){
cout << getName() << " has died" << endl;
}
}
void printBunny()
{
cout << "Name: " << getName() << endl;
cout << "Sex: " << getSex() << endl;
cout << "Color: " << getColor() << endl;
cout << "Age: " << getAge() << endl;
}
};

int main()
{
vector< Bunny > colony;
char quit = '\0';
do
{
// Add more bunny
for (int i = 0; i < 5; i++)
{
colony.push_back(Bunny());
}
// Print all the bunny
for (int i =0; i < colony.size(); i++)
{
colony[i].printBunny();
colony[i].deleteBunny();
cout << endl;
}
cout << "You have a total of " << colony.size() << " bunnies\n";
cout << "Press a key to add more bunny, q to quit\n";
quit = cin.get();
cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// repeat
} while (quit != 'q' && quit != 'Q');

return 0;
}

最佳答案

你必须使用 erase remove idiom :

std::erase(colony.remove_if( colony.begin(), colony.end(),
[] (bunny& oldBunny){ return oldBunny.age > 10; } ), colony.end());

关于c++ - 从 vector 中删除一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42894869/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com