我有实例的向量,类似
class A;
class B : public A;
class C : public A;
class D : public A;
A * a1 = new A;
A * a2 = new A;
A * b1 = new B;
A * b2 = new B;
A * c = new C;
A * d = new D;
std::vector<A *> data = {a1, b1, b2, c, a2, d};
是否可以重新排列数组,以便类型的顺序由模式给出? Somethng喜欢:
pattern1: A, B, C, D
result1: {a1, a2, b1, b2, c, d}
pattern2: A, D, B, C
result2: {a1, a2, d, b1, b2, c}
模式只是一种模式,所以它告诉我们,A在B之前等等。这是否可以解决(C ++ 11或C ++ 14)而不需要修改现有的类?
答案 0 :(得分:2)
您可以使用std::type_index
来定义订单,然后只使用stable_
)sort
。
struct A { virtual ~A() = default; }; // you need virtual method for typeid operator to look at dynamic type.
struct B : A {};
struct C : A {};
struct D : A {};
A * a1 = new A;
A * a2 = new A;
A * b1 = new B;
A * b2 = new B;
A * c = new C;
A * d = new D;
template<typename T>
void rearrange(T begin, T end)
{
std::vector<std::type_index> order = { std::type_index(typeid(*a1)), std::type_index(typeid(*b1)), std::type_index(typeid(*c)), std::type_index(typeid(*d)) };
std::stable_sort(begin, end, [&](const A* lhs, const A* rhs)
{
return std::find(order.begin(), order.end(), std::type_index(typeid(*lhs))) < std::find(order.begin(), order.end(), std::type_index(typeid(*rhs)));
});
}
在coliru上查看。
答案 1 :(得分:0)
if(typeid(a)== typeid(b)){
cout&lt;&lt; &#34;这里的类型相同\ n&#34;;
}
string s = typeid(someClassInst).name();