[英]I'm getting std class vector has no member error for all my vector methods
[英]My vector is sorted and yet I'm getting a “sequence not ordered” error
是否存在std::sort
失敗的情況?
我有一個std::vector<KeyValPair<T>> queue
,我用它來完成以下操作
std::sort(queue.begin(), queue.end());
std::pair<iterator, iterator> match =
std::equal_range(queue.begin(), queue.end(), cost);
確切地說。 然后有時,並非總是如此,我得到一個“序列未訂購”的錯誤。
文檔描述sort
和equal_range
使用相同的比較函數,所以我很困惑矢量如何變得無序。
vector
類型是具有自定義比較運算符的以下類。
template<typename T>
class KeyValPair: public std::pair<double, T>
{
public:
KeyValPair(double d, T t): std::pair<double, T>(d, t){};
bool operator<(const KeyValPair<T>& rhs) const
{
return first < rhs.first;
}
bool operator==(const KeyValPair<T>& rhs) const
{
return second == rhs.second;
}
};
template<typename T>
bool operator< (const KeyValPair<T>& lhs, const double& rhs) {return lhs.first < rhs;};
template<typename T>
bool operator< (const double& lhs, const KeyValPair<T>& rhs) {return lhs < rhs.first;};
比較功能會以某種方式失敗嗎? 還有什么可以導致這個錯誤?
首先由@ecatmur精神上檢測到,你的問題是你正在使用<
on double
s,並且你的一個或多個double
s是NaN
。
安全double
訂購如下:
struct safe_double_order {
bool operator()(double lhs, double rhs) const {
if ((lhs != lhs) || (rhs != rhs)) // NaN detector
return (lhs!=lhs)>(rhs!=rhs); // order NaN less than everything, including -infinity
return lhs < rhs;
}
};
接下來,我們可以編寫一個密鑰分揀機:
template<class K, class O=std::less<K>>
struct key_sorter {
struct helper {
K const& k;
helper( K const& o ):k(o) {}
template<typename V>
helper( std::pair<K, V> const& o ):k(o.first) {}
bool operator<( helper const& o ) const {
return O{}( k, k.o );
}
};
bool operator()( helper lhs, helper rhs ) const {
return lhs < rhs;
}
};
它傳遞了一個鍵類型和一個可選的排序仿函數,可以直接使用Key
類型搜索/排序std::pair<Key,?>
。
std::vector< std::pair<double, X> > vec;
std::sort( vec.begin(), vec.end(), key_sorter<double, safe_double_order>{} );
auto match = std::equal_range( vec.begin(), vec.end(), value, key_sorter<double, safe_double_order>{} );
上面有一些C ++ 11主義,但如果你使用C ++ 03,一般的設計應該是清楚的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.