gpt4 book ai didi

c++ - 连续迭代多个列表(C++)

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:36:46 26 4
gpt4 key购买 nike

我有 3 个类,其中 2 个像这样从另一个继承:

class A {
public:
virtual void foo() {cout << "I am A!" << endl;}
};

class B : public A {
public:
void foo() {cout << "B pretending to be A." << endl}
void onlyBFoo() {cout << "I am B!" << endl}
};

class C : public A {
public:
void foo() {cout << "C pretending to be A." << endl}
void onlyCFoo() {cout << "I am C!" << endl}
};

我想做的是这样的:

list<A*> list_of_A;
list<B*> list_of_B;
list<C*> list_of_C;

//put three of each class in their respective list

cout << "First loop:" << endl;
for (list<B>::iterator it = list_of_B.begin(); it != list_of_B.end(); ++it) {
(*it)->onlyBFoo();
}

cout << "Second loop:" << endl;
for (list<C>::iterator it = list_of_C.begin(); it != list_of_C.end(); ++it) {
(*it)->onlyCFoo();
}

//This part I am not sure about
cout << "Third loop:" << endl;
for (Iterate all 3 loops i.e. *it points to As, then Bs then Cs) {
(*it)->foo();
}

输出:

First loop:
I am B!
I am B!
I am B!

Second loop:
I am C!
I am C!
I am C!

Third loop:
I am A!
I am A!
I am A!
B pretending to be A.
B pretending to be A.
B pretending to be A.
C pretending to be A.
C pretending to be A.
C pretending to be A.

即有时我只想迭代 B 对象,但有时我想迭代所有对象。

一个解决方案是将它们全部存储在一个列表中,但是我希望能够按类型顺序遍历它们,即 As 然后 Bs 然后 Cs。

另一个建议的解决方案是使用迭代器或 iterator_adapters,但是我以前从未使用过它们,也找不到一个简单的例子来帮助我开始使用它们。

最佳答案

提升 iterator adapters可能会给你你需要的东西——你可以创建一个多态列表(所有项目),然后创建迭代器适配器,只迭代 B 项目,或只迭代 C 项目。您可以使用标准迭代器列出所有项目。

正如其他人所提到的,您需要多态列表来包含指针,这样您的项目就不会被分割。然后您需要管理项目的生命周期,即确保在删除容器时删除它们。有智能指针类可以使该任务更容易。

关于c++ - 连续迭代多个列表(C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2890013/

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