简体   繁体   English

按类型对std :: vector进行排序

[英]Sort a std::vector by type

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. 我正在观看http://channel9.msdn.com/Events/GoingNative/2013/Writing-Quick-Code-in-Cpp-快速和大约36分钟,他们谈论按照元素类型对集合进行排序的好处如果你打算在它们上调用虚方法。

So given 所以给定

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

vector<Base *> myVector;

How could you sort myVector in such a way that the elements of each type are all adjecent? 你怎么可以这样排序myVector以这样一种方式,每种类型的元素都是adjecent?

Is there any way to do that without using a virtual function in order to indentify each derived type? 如果不使用虚函数来识别每个派生类型,有没有办法做到这一点? (Maybe using typeid ?) (也许使用typeid ?)

You can use type_index for this. 您可以使用type_index You constructing one from a type_info object that's returned from typeid operator. 您从typeid运算符返回的type_info对象构造一个。 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. 它是一个具有重载关系运算符的类,具有良好定义的排序,因此它在关联容器等中作为键类型很有用。

Here's an example: 这是一个例子:

#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(); }
}

The output is: 输出是:

D1
D1
D2
D2
D3
D3

You specify the comparison function. 您指定比较功能。 For more details on that, see for example Sorting an STL vector on two values . 有关详细信息,请参阅例如在两个值上对STL向量进行排序

Inside the comparison function you can write whatever you want. 在比较功能中,您可以编写任何您想要的内容。 It can compare whatever properties of your objects. 它可以比较对象的任何属性。 In particular, it can compare one specific value obtained via a virtual function, such as getType() , which may return 1 in Der1 , 2 in Der2 and 3 in Der 3 . 特别是,它可以比较通过一个虚拟函数,如获得的一个特定值getType()其可在返回1 Der1 ,2 Der2和3中Der 3

You could implement a virtual function, say prio which returns the priority (an int ) among the types; 你可以实现一个虚函数,比如prio ,它返回类型中的优先级( int ); prio would be suitably implemented in the derived classes. prio将适当地在派生类中实现。 Then implement a comparator which would evaluate prio on two instances of Base to compare them. 然后实现一个比较器,将评估prio上的两个实例Base对它们进行比较。

These are just possibilities, there is not one true answer to this. 这些只是可能性,没有一个真正的答案。

Sorting? 排序?

The main problem of sorting is finding a key upon which to sort. 排序的主要问题是找到要排序的密钥。 This is "phase 1", if you want. 如果你愿意,这是“第1阶段”。 Phase 2 is using a generic sorting from the standard library and is often easier than phase 1. 阶段2使用标准库中的通用排序,并且通常比阶段1更容易。

Keying 键控

One possibility is to use typeid / type_info . 一种可能性是使用typeid / type_info

Instances of type_info define operator == and operator != , as well as a hash_code member function. type_info实例定义operator ==operator != ,以及hash_code成员函数。

Sorting 排序

Use a generic sort algorithm from the standard algorithm. 使用标准算法中的通用排序算法。 As the key for sorting you could use eg the value returned from the hash_code function. 作为排序的关键,您可以使用例如hash_code函数返回的值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM