如何使用 std::find 与不是 std::less 的<运算符一起使用
how to use std::find with an < operator that is not std::less
说我有
class newVector: public std::vector<T> {
public:
bool operator< (const newVector& v) {
//..
}
};
和
a std::set<newVector>;
我无法正确使用.find(…),我不确定要在(…)中放入什么才能使用newVector::运算符<。当我只放.find(元素)时,它使用std::less。我应该以某种方式更改std::less吗?
暂时忽略从std::vector
派生是个坏主意,我可以想出以下方法来解决这个问题:
-
为
newVector
的对象定义operator<
。class newVector: public std::vector<T> { public: bool operator< (const newVector& v) const { //.. }
和
std::set<newVector> a; a.find(...);
-
定义一个具有适当
operator()
函数的函子,并使用它来创建std::set
。template <typename T> struct NewVectorLess { bool operator()(newVector<T> const& lhs, newVector<T> const& rhs) { // ... } };
和
std::set<newVector<int>, NewVectorLess<int>> a; a.find(...);
您不需要重载向量,也不需要更改std::less,而是单独定义您自己的std::less兼容函数对象。
#include <iostream>
#include <vector>
#include <set>
using namespace std;
struct OppositeVectorComp
{
template< class T, class Alloc >
bool operator()( const std::vector<T,Alloc>& lhs,const std::vector<T,Alloc>& rhs )
{
return !(lhs < rhs);
}
};
int main() {
std::vector<int> a , b;
std::set<std::vector<int>> defaultset;
std::set<std::vector<int>, OppositeVectorComp> myset;
a.push_back(1);
b.push_back(2);
myset.insert(a);
myset.insert(b);
defaultset.insert(a);
defaultset.insert(b);
std::cout << (*myset.begin())[0] << std::endl; // output 2
std::cout << (*defaultset.begin())[0] << std::endl; // output 1
return 0;
}
这里OppositeVectorComp
定义了向量上的一个新阶,其中
OppositeVectorComp(a,b) true iff a <b is false
通过使用类型std::set<std::vector<int>, OppositeVectorComp>
,我们定义了一个使用自定义std::less的集合。
相关文章:
- 使用std::multimap迭代器创建std::list
- C++中std::resize(n)和std::shrink_to_fit之间的区别
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- 错误:调用"std::vector<:vector<int>>::p ush_back(std::vector<std::__cxx11::basic_string<
- C 建造者Clang STD :: Sill,找不到超载的操作员&lt;
- 为什么STD :: MAP需要操作员&lt;以及我如何写一个
- std::vector::reserve(未知m),我知道m<<;N(通常)并且知道N
- std::vector<;uint8_t>;当C++11/14启用时,手动复制而不是调用memcpy
- C++运算符<<调用::ostream而不是std::osttream
- 是std :: set&lt; std :: future&gt;不可能存在
- 在修改列表后,std :: list&lt; t&gt; :: end()的值是否会更改
- BOOST ::变体无法解决运算符&lt;&lt;对于STD :: Ostream
- C++重载<<具有typedef'd std::vector
- 以x的倍数填充前导零,使用std::cout<<std::十六进制
- 错误:没有匹配'运算符<<"在'std::cout
- std::pair的默认构造函数<>将基本类型(int等)设置为零
- std::ostream&operator< & lt; (std:: ostream&压力,压力& &;val)
- 将std::endl传递给std::operator<<
- std::映射<>或std::vector<>在处理大型标志集时
- 重载& lt; & lt;使用命名空间std