有没有更好的方法从 C++ 中自定义(即用户定义)对象的排序数组创建成员变量的排序数组?
示例 -
class People{
public:
//can have multiple parameters. What are the options in either case?
unsigned int birth_year;
};
假设我们有一个 std::vector<People>
的数组我们想得到 std::vector<unsigned int>
按出生年份排序。
我们可以使用多种方法之一根据此链接中提到的 birth_year 对自定义对象进行排序 - Sorting a vector of custom objects .
现在,如果我们需要获得排序后的出生年份 vector ,我们将不得不遍历排序后的人物 vector 并将其插入一个新的无符号整数 vector 。
有没有更快的方法(使用内存偏移等)?或者 C++11 中是否有我们可以利用的功能?
最佳答案
您的问题相当不明确。所以这里有一些假设和可能的解决方案
您的 vector 已经按出生日期排序
在那种情况下,如果你真的想快点,只需使用reinterpret_cast
。这是邪恶的,但如果您的 Person
类真的只包含一个成员,那么它肯定是最快的。
您的Person
类的成员不仅仅是birth_date
使用带有 lambda 的转换。
std::vector<unsigned int> vec2;
vec2.reserve(vec1.size());
transform(vec1.begin(), vec1.end(),
back_inserter(vec2),
[](const Person& p) { return p.birth_date; });
你只想从新 vector 中读取
在这种情况下,您可以考虑使用 View (而不是 vector ),例如参见 https://github.com/ericniebler/range-v3
关于C++从排序的对象数组创建排序数组的最佳方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35028349/