从具有自定义排序的向量创建集合

Creating a Set from a Vector with custom sort

本文关键字:向量 创建 集合 排序 自定义      更新时间:2023-10-16

>我正在尝试从给定的 Vector 创建一个集合,它采用自定义排序来存储元素。我尝试做的一种方法是使用 customSortFncset<string> my_set(my_comp)创建一个集合,并遍历向量并将每个向量添加到集合中。取而代之的是,是否有一个简短的手(它删除了编写 for 循环来迭代向量(来做同样的事情?

例如: 如果我Vector<string>vector<string> words = {"a","b","ba","bca","bda","bdca"};该集合应具有按长度排序的顺序存储的唯一值,其中最长的字符串排在最前面。

预期集输出 =>{"bdca", "bda", "bca", "ba", "b", "a"}

另外,尝试使用自定义排序功能将vector<CustomClass>转换为set<CustomClass>时如何执行此操作。

使用一系列迭代器的构造函数。像这样:

#include <set>
#include <string>
#include <vector>
#include <iostream>
struct my_sorter {
bool operator()(const std::string &a, const std::string &b) const noexcept {
if (a.length() == b.length()) {
return a > b;
} else {
return a.length() > b.length();
}      
}
};
int main() {
std::vector<std::string> words = {"a","b","ba","bca","bda","bdca"};
std::set<std::string, my_sorter> wordset(words.begin(), words.end());
for (const auto &s : wordset) {
std::cout << s << ' ';
}
std::cout << 'n';

return 0;
}

是的,像这样

set<string> my_set(words.begin(), words.end(), my_comp);

大多数 STL 集合都有一个构造函数,它接受一对迭代器。因此,从另一个集合的元素填充一个集合非常容易。

当您有一个自定义类时,完全相同的代码将起作用(假设my_comp适用于自定义类(。