【发布时间】:2021-02-17 13:30:54
【问题描述】:
我创建了这个类,我需要使用 for(迭代器)来输入值,它们不一定是 i,任何其他值,因为我需要使用列表:
#include <iostream>
#include <list>
using namespace std;
// 1ra clase base
class Person {
int e;
public:
Person(int);
void printDates();
};
Person::Person(int x) { e = x; }
void Person::printDates() { cout << e; }
int main() {
list<Person> persons;
for (int i = 0; i < 5; i++) {
Person person(i);
persons.push_front(person);
}
// for(int i = 0; i < 5; i++)
// {
// hombres[i].printDates();
// }
}
我需要使用 personDates 方法,以及您可以添加的任何其他方法,无论是在列表中还是在另一个列表中。
【问题讨论】:
-
for( auto& person : persons) { // do something with person }在线示例:https://ideone.com/8lEv0C -
“输入值”是什么意思?什么是“personDates 方法”?你的意思是
printDates()?您使用的 for 循环有什么问题? -
也许您需要for each loop?
-
谢谢你,写下你的答案,我会在答案中评价它@drescherjm
-
你为什么还要使用
std::list?请改用std::vector,因为它几乎在所有方面都更胜一筹。而且你不需要push_front。
标签: c++