从具有自定义排序的向量创建集合
Creating a Set from a Vector with custom sort
>我正在尝试从给定的 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适用于自定义类(。
相关文章:
- 从具有自定义排序的向量创建集合
- 我正在寻找一种优雅的方式来从元组向量创建tuple_element向量
- 从类指针的向量创建成员变量的向量
- 从 c++ 中的字符串向量创建一个元组
- 如何在 c++ 中从两个向量创建 JSON 对象?
- 如何在不迭代的情况下从string_view向量创建字符串向量?
- 通过移动从两个向量创建元组向量
- 为结构的向量创建C 矢量迭代器
- C 矢量元素擦除与新向量创建
- 使用向量的向量创建一个尺寸
- C MultiSet从排序的向量创建
- 从向量<T>创建一组字符串
- 使用C 中的向量创建整数集类别
- 从两个原始向量创建一个“特征::矩阵”
- 用向量创建筛子
- 从Vectores的向量创建一个板
- C++内存管理:从函数中的向量创建一个新数组
- 正在使用类中的向量创建类
- 为向量创建临时变量
- 如何在c++中使用模板图类中的向量创建邻接矩阵