C++ 如何将std::find与<;不是std::less的运算符
说我有C++ 如何将std::find与<;不是std::less的运算符,c++,stdset,C++,Stdset,说我有 class newVector: public std::vector<T> { public: bool operator< (const newVector& v) { //.. } }; class newVector:public std::vector{ 公众: 布尔运算符
class newVector: public std::vector<T> {
public:
bool operator< (const newVector& v) {
//..
}
};
class newVector:public std::vector{
公众:
布尔运算符<(const newVector&v){
//..
}
};
及
a std::set;
我无法正确使用a.find(…),我不确定在(…)中放入什么以便使用newVector::operator暂时忽略从
std::vector
派生是个坏主意,我可以想出以下方法来解决此问题:
操作符您不需要重载向量,也不需要更改std::less,只需要单独定义自己的
通过使用类型std::set
我们定义了一个使用自定义std::less的集合 我的问题是为什么要从std::vector
派生?从std::vector
或任何标准库类派生是个坏主意我想在std::vector中添加一些东西。有人告诉我作文更好,但这不应该被禁止?嗯……是的,这是被禁止的(在指导原则方面)。Scott Meyers在有效的C++@myelf中讨论了这一点,而不是听这个“某人”,研究从std::vector
派生不是一个好主意的原因?我不明白第一个,我想里面有一个常数,但除此之外什么都没有改变。@myelf,是的。这是两种选择。在您发布的代码中,您不仅错过了常量
,而且参数类型是不精确向量
。哦,那个不精确向量是错误编辑的产物。非常感谢。
a std::set<newVector>;
class newVector: public std::vector<T> {
public:
bool operator< (const newVector& v) const {
//..
}
std::set<newVector> a;
a.find(...);
template <typename T>
struct NewVectorLess
{
bool operator()(newVector<T> const& lhs, newVector<T> const& rhs)
{
// ...
}
};
std::set<newVector<int>, NewVectorLess<int>> a;
a.find(...);
#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(a,b) true iff a <b is false