gpt4 book ai didi

c++ - 我可以在不查看每个元素的情况下将 std::vector 转换为 std::vector 吗?

转载 作者:可可西里 更新时间:2023-11-01 17:38:42 26 4
gpt4 key购买 nike

我有一个基类,有几个扩展它的类。我有一些通用库实用程序,它们创建一个包含指向基类的指针的 vector ,以便任何子类都可以工作。如何将 vector 的所有元素都转换为特定的子类?

// A method is called that assumes that a vector containing
// Dogs casted to Animal is passed.
void myDogCallback(vector<Animal*> &animals) {
// I want to cast all of the elements of animals to
// be dogs.
vector<Dog*> dogs = castAsDogs(animals);
}

我天真的解决方案看起来像这样:

// A method is called that assumes that a vector containing
// Dogs casted to Animal is passed.
void myDogCallback(vector<Animal*> &animals) {
// I want to cast all of the elements of animals to
// be dogs.
vector<Dog*> dogs;
vector<Animal*>::iterator iter;
for ( iter = animals.begin(); iter != animals.end(); ++iter ) {
dogs.push_back(dynamic_cast<Dog*>(*iter));
}
}

最佳答案

您可以使用 std::transform。它仍然在内部使用 for(),但是你会得到两个字符串的实现:

#include <vector>
#include <algorithm>
using namespace std;

struct Animal { virtual ~Animal() {} };
struct Dog : Animal { virtual ~Dog() {} };

template<typename Target>
struct Animal2Target { Target* operator ()( Animal* value ) const { return dynamic_cast<Target*>(value); } };

void myDogCallback(vector<Animal*> &animals) {
{
vector<Dog*> dogs;
transform( animals.begin(), animals.end(), dogs.begin(), Animal2Target<Dog>() );
}

关于c++ - 我可以在不查看每个元素的情况下将 std::vector<Animal*> 转换为 std::vector<Dog*> 吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1175628/

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