[英]std::out_of_range during std::sort with custom comparator
我有以下代碼
template<typename T>
bool GenericCompare(T lhs, T rhs)
{
return lhs < rhs;
}
template<typename T>
class SortOrder
{
public:
SortOrder(const std::vector<T> *_sortArray,
bool (*_comparator)(T,T) = GenericCompare) :
sortArray(_sortArray) , comparator (_comparator) , customOperator(true) {;}
bool operator()(int lhs=0, int rhs=0) const
{
bool res;
try {
sortArray->at(lhs);
}
catch (std::out_of_range& oor) {
std::cout << "LHS Out of range: " << lhs << " : " << rhs
<< " " << oor.what() << std::endl;
}
try {
sortArray->at(rhs);
}
catch (std::out_of_range& oor) {
std::cout << "RHS Out of range: " << lhs << " : "
<< rhs << " "<< oor.what() << std::endl;
}
// Always needs comparator
res = comparator(sortArray->at(lhs),sortArray->at(rhs));
return res;
}
private:
const std::vector<T> *sortArray;
bool (*comparator)(T,T);
bool customOperator;
};
現在我有一個簡單的排序代碼,我在其中根據另一個為double的向量對索引向量進行排序。 'circle_fwd_vector'是包含所有雙打的向量。
for (int i=0;i<circle_fwd_vector.size();i++) {
circle_index_vector.push_back(i);
}
try {
std::sort(circle_index_vector.begin(),circle_index_vector.end(),
SortOrder<double>(&circle_fwd_vector));
}
catch (std::exception& e)
{
std::cout << e.what() << std::endl;
}
現在在控制台中,我得到這樣的結果:
RHS Out of range: 1711 : 1079615151 vector::_M_range_check
由於我沒有使用任何自定義類,我正在排序的矢量基於雙打,我不確定為什么我會超出范圍。 我確定雙向量中沒有無窮大,但即使有,也不應該std :: sort仍然給我正確的排序索引而不退出索引?
感謝您的任何幫助。
編輯:如果有幫助,這是發生這種情況時向量的數據轉儲。 http://pastebin.com/7wLX63FJ另外,我正在使用Xcode 3.2.6附帶的GCC 4.2進行編譯。
此錯誤是由數據中的nan
值引起的(位置1688)。 問題是當你包含nan
時, <
不再滿足std::sort
所需的約束。 有關所有比較器必須滿足的“嚴格弱排序”的定義,請參見標准25.4 / 4。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.