按类型对std :: vector进行排序 [英] Sort a std::vector by type

查看:419
本文介绍了按类型对std :: vector进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在观看 http:// channel9 .msdn.com / Events / GoingNative / 2013 / Writing-Quick-Code-in-Cpp-Quickly 和大约36分钟,他们谈论了按照元素类型对集合进行排序的好处,如果你要去

I was watching http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-Quickly and around min 36, they talk about the benefits of sorting a collection by the type of its elements if you are going to be calling virtual methods on them.

So given

Base {};
class Der1:public Base {};
class Der2:public Base {};
class Der3:public Base {};

vector< Base *> myVector;

class Base {}; class Der1 : public Base {}; class Der2 : public Base {}; class Der3 : public Base {}; vector<Base *> myVector;

如何排序 myVector 每种类型的元素都是adjecent的方式?

How could you sort myVector in such a way that the elements of each type are all adjecent?

有没有办法做到这一点,而不使用虚函数来标识每个派生类型? (可能使用 typeid ?)

Is there any way to do that without using a virtual function in order to indentify each derived type? (Maybe using typeid?)

推荐答案

=http://en.cppreference.com/w/cpp/types/type_index> type_index 。您从 typeid 运算符返回的 type_info 对象构造一个。它是一个具有重载的关系运算符的类,具有良好定义的顺序,因此它在关联容器等中用作关键类型。

You can use type_index for this. You constructing one from a type_info object that's returned from typeid operator. It's a class with overloaded relational operators with well defined ordering, so that it is useful as a key type in associative containers and alike.

这是一个例子:

#include <typeinfo>
#include <typeindex>
#include <vector>
#include <algorithm>
#include <iostream>

struct Base {
    virtual ~Base() {}
    virtual const char* who() = 0;
};
struct D1 : Base { const char* who() { return "D1\n"; } };
struct D2 : Base { const char* who() { return "D2\n"; } };
struct D3 : Base { const char* who() { return "D3\n"; } };

int main()
{
    std::vector<Base*> vec { new D2, new D1, new D3, new D3, new D1, new D2 };
    std::sort( vec.begin(), vec.end(),
    [](const Base* p1, const Base* p2)
    {
        return
            std::type_index(typeid(*p1)) <
            std::type_index(typeid(*p2));
    });

    for (auto p : vec) { std::cout << p->who(); }
}

输出为:

D1
D1
D2
D2
D3
D3

这篇关于按类型对std :: vector进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆