kal*_*ari -1 c++ sorting vector
我试图按照以下方式对此进行排序xValue:
Item
side: L
xValue:2
label: 0
yValue: 50
Item
side: R
xValue:10
label: 0
yValue: 50
Item
side: L
xValue:35
label: 1
yValue: 20
Item
side: R
xValue:55
label: 1
yValue: 20
Item
side: L
xValue:30
label: 2
yValue: 60
Item
side: R
xValue:45
label: 2
yValue: 60
Run Code Online (Sandbox Code Playgroud)
在Item.cpp,我重载了运营商<:
bool Item::operator < (const Item& itm) const{
return (xValue < itm.xValue);
}
Run Code Online (Sandbox Code Playgroud)
这就是我的用法std::sort:
sort(mainList.begin(), mainList.end());
Run Code Online (Sandbox Code Playgroud)
但结果是:
Item
side: L
xValue:2
label: 0
yValue: 50
Item
side: L
xValue:35
label: 1
yValue: 20
Item
side: R
xValue:10
label: 0
yValue: 50
Item
side: R
xValue:55
label: 1
yValue: 20
Item
side: L
xValue:30
label: 2
yValue: 60
Item
side: R
xValue:45
label: 2
yValue: 60
Run Code Online (Sandbox Code Playgroud)
这有什么不对?
编辑: mainList:
vector<Item*> mainList;
Run Code Online (Sandbox Code Playgroud)
mainList插入:
if (myfile.is_open()){
// read building count
getline(myfile,line);
buildingCount = atoi(split(line)[0].c_str());
// read buildings
for (int b=0; b < buildingCount; b++){
getline(myfile,line);
mainList.push_back(new Item('L', atoi(split(line)[0].c_str()), b, atoi(split(line)[1].c_str())));
mainList.push_back(new Item('R', atoi(split(line)[2].c_str()), b, atoi(split(line)[1].c_str())));
}
}
Run Code Online (Sandbox Code Playgroud)
您需要一个仿函数进行比较,并将其作为第三个参数排序:
http://www.cplusplus.com/forum/general/59164/
struct Compare {
bool operator() (const Item* left, const Item* right) const {
return left->xValue < right->xValue;
}
}
sort(mainList.begin(), mainList.end(), Compare());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1980 次 |
| 最近记录: |