C++ - 使用额外参数进行排序
C++ - Sorting with an extra parameter
我正在使用邻接列表和使用以下类型定义定义的映射:
typedef vector<list<Edge> > adjacencyList;
typedef map<int,WikiPage> idToWikiMap;
我想按名称对邻接列表(adjacencyList
)进行排序。adjacencyList
的索引映射到我的地图中的一对。例如
adjacencyList lst;
lst[0] = NULL
lst[1] = list of edges related to City1
lst[2] = list of edges related to City2
idToWikiMap mymap;
mymap[1] -> Name of City1
mymap[2] -> Name of City2
因此,我想使用与邻接列表索引相关的地图中的名称对邻接列表进行排序。我想出了以下代码。由于我的比较函数需要映射,所以我不能只创建一个普通函数。所以我用了struct
和Local
.
比较有效。我可以cout
当前正在比较的列表的名称和返回值。例如,我得到
Comparing Chicago and New York
Smaller: 0
Comparing Montreal and Chicago
Smaller: 1
Comparing Montreal and New York
Smaller: 0
Comparing Toronto and Chicago
Smaller: 1
Comparing Toronto and Montreal
Smaller: 1
Comparing Toronto and New York
Smaller: 1
Comparing Miami and Chicago
Smaller: 1
Comparing Miami and Montreal
Smaller: 0
但是,原始版本不会被修改...我做错了什么吗?
void printOrganized(adjacencyList& lst, idToWikiMap page_ofID) {
// Define compare functions that accepts idToWikiMap parameter
struct Local {
Local(idToWikiMap mymap) { this->mymap = mymap; }
bool operator() (const list<Edge>& l1, list<Edge>&l2)
{ return mymap.at(l1.front().origin).title < mymap.at(l2.front().origin).title; }
idToWikiMap mymap;
};
/* Sort adjacenyList lst */
sort (lst.begin()+1, lst.end(), Local(page_ofID));
...
}
在我修复编译错误后,您的代码对我来说效果很好。也许您的编译器没有报告此错误,但它导致您的代码无法正常工作?
无论如何,错误出在比较函数中 - 您应该将两个参数都作为 const 引用,即
bool operator() (const list<Edge>& l1, const list<Edge>& l2)
此外,我不得不Local
移动到全局范围,因为只要它在函数中定义,它就对我不起作用。您可以在此处查看工作结果:http://ideone.com/e.js/UPMeFm
相关文章:
- Constexpr 可变参数模板,用于对无符号整数进行重新排序
- 是否可以在调用链接器时强制 CMake 重新排序参数?
- C++17.处理使用 auto 相关的模板参数.代码排序困难
- 在C++排序中为比较函数指定参数
- 推力中的参数排序
- C++一个具有 2 个参数(___ _____,整数长度)的函数中的快速排序
- 函数参数:不确定排序还是未排序?
- 用于对可变数量的数组进行排序的可变参数模板
- 提升 MPL 排序模板参数包
- 按参数对向量进行排序
- 五个中三个最大参数的平均值,不使用排序算法或向量/数组
- 根据一个参数对数组进行排序
- 对于列表排序,有没有办法使用相同的参数让多个运算符重载?
- 通过提供指针数组作为参数对数组进行排序
- 使用按插入方式排序的参数创建哈希映射
- C++:如何使用类参数之一对派生自类的对象向量进行排序
- STL 按多个参数C++排序
- 谷歌C++风格指南.为什么要先输入后输出参数排序
- IDL文件和C++头文件中的defaultvalue和retval参数排序
- 基于额外参数排序向量