我知道堆是如何工作的以及它如何排列最小和最大元素。如果vector仅包含int
,则很容易在STL中应用make_heap。但如果向量包含字符串和int结构,如何应用make_heap()
。我想根据int
的值来构造堆。 请告诉我该怎么做。C++ STL - make_heap with pair <int,string> as data type
回答
你必须为你的结构提供比较函数:
struct A
{
int x, y;
};
struct Comp
{
bool operator()(const A& s1, const A& s2)
{
return s1.x < s2.x && s1.y == s2.y;
}
};
std::vector<A> vec;
std::make_heap(vec.begin(), vec.end(), Comp());
为什么比较器中的第二个条件('s1.y == s2.y')? – jogojapan
它只是一个例子,不关心比较逻辑 –
我不认为比较函数有任何需要,除非你想指定你自己的逻辑。如果您想要进行字典比较,只需使用默认值即可。 – juanchopanza
是的,你可以使用std::make_heap
与std::pair<int, std::string>
直接,因为std::pair
具有所需的小于比较operator<
。甚至在上面引用的例子中使用了std::pair
的特定实例。
- 1. 如何对矢量<pair <int,pair <int,pair <string,pair <int , int >>>>>进行排序
- 2. std :: make_heap with pairs
- 3. C++ STL make_heap和pop_heap不工作
- 4. STL priority_queue <pair> vs. map
- 5. 如何使用vector <pair <int,pair <int,int> >>进行排序?
- 6. HTML <input type =“text”... as <input type =“file”
- 7. 在C++中使用映射<pair <int,int>,string>
- 8. 从vector <pair <double *,pair <double *,int * >>到数组的C++转换
- 9. 如何对一个向量进行排序<pair <string,pair <int , int> >>?
- 10. 为什么std :: pair <int, int>可以从const std :: pair <int, float>&?
- 11. C++ STL map,std :: pair作为密钥
- 12. 为何'is_convertible'在<utility> std :: pair(STL)?
- 13. vector <pair <int,unordered_set <int> >>为对
- 14. C++:如何使用std :: less <int> with boost :: bind和boost :: lambda?
- 15. FourCC as int C#
- 16. data(with eval)as jquery-method的参数
- 17. Javax.persistence with @Entity bean save int [] as bytea(postgres)
- 18. 调用'(std :: pair <unsigned int,unsigned int>)(unsigned int&,unsigned int)'
- 19. std :: vector <std :: pair <int,std :: pair <bone,std :: string> >>不按int整理?
- 20. 无法使用对<int, int>作为C++中的键集STL
- 21. C#LINQ存储int? as int
- 22. Cast StringCollection as List <int>
- 23. std :: pair <int, int> vs两个int的结构
- 24. 如何定义,初始化和使用 - vector <vector <pair < int,int >,int>> v in C++?
- 25. 'struct std :: pair <int, int>'has no member named'serialize'
- 26. 实施Dijkstra算法使用STL make_heap
- 27. C++:STL multimap.equal_range()
- 28. 使用pair with accumulate时出现问题
- 29. Q设置<data type>了的QList
- 30. C++:矢量<对<vector<int>,INT>>
你有什么试过?特别是,你是否尝试给出一个明确的比较函数? – rici
我不知道如何处理比较的乐趣... –
自从我看了一段时间以来,已经有一段时间了,但是'pair'不是按照你想要的顺序来做的吗? – Hurkyl