I'm trying to implement the compare operator of a class that inherits from vector.
I want it to compare first its own new attributes and then use the inherited operator from vector. This is an example:
struct A : vector<int> {
int a;
bool operator==(const A& other) {
return a == other.a && vector::operator==(other);
}
}
But I'm getting this error:
no member named 'operator==' in 'std::__1::vector<int, std::__1::allocator<int> >'
Same result with other classes from the STL, but it works well if I inherit from another class of my own.
This is the implementation of vector that I'm using:
inline _LIBCPP_INLINE_VISIBILITY
bool
operator==(const vector<_Tp, _Allocator>& __x, const vector<_Tp, _Allocator>& __y)
{
const typename vector<_Tp, _Allocator>::size_type __sz = __x.size();
return __sz == __y.size() && _VSTD::equal(__x.begin(), __x.end(), __y.begin());
}
What I'm doing wrong?
vector's equality operator is a non-member function, which means you can't call it like that. You would be better off doing something like:
struct A : std::vector<int> {
int a;
bool operator==(const A& other) {
vector const& self = *this;
return a == other.a && self == other;
}
};
However, I wouldn't recommend inheriting from a standard container. Instead, you should have a std::vector<int> data member (composition over inheritance).
Related
In libstdc++3, in the header bits/stl_iterator.h (GCC 10 source here), every binary operator for __normal_iterator has two overloads defined (here is == for example):
template<typename _IteratorL, typename _IteratorR, typename _Container>
_GLIBCXX20_CONSTEXPR
inline bool
operator==(const __normal_iterator<_IteratorL, _Container>& __lhs,
const __normal_iterator<_IteratorR, _Container>& __rhs)
_GLIBCXX_NOEXCEPT
{ return __lhs.base() == __rhs.base(); }
template<typename _Iterator, typename _Container>
_GLIBCXX20_CONSTEXPR
inline bool
operator==(const __normal_iterator<_Iterator, _Container>& __lhs,
const __normal_iterator<_Iterator, _Container>& __rhs)
_GLIBCXX_NOEXCEPT
{ return __lhs.base() == __rhs.base(); }
Where .base() returns a pointer to an array element in this case. This is done throughout the library for other iterator types as well. According to comments and changelogs scattered throughout, it's done to support interoperability between iterators and const_iterators.
My question is, why are both the the <_IteratorL, _IteratorR, _Container> and <_Iterator, _Container> overloads defined for all of them? That is, why is <_Iterator, _Container> necessary? Wouldn't the former cover every case? What would break if the latter was removed?
GCC's libstdc++ implementation has a lot of street cred, so I'm sure there's a good, possibly subtle reason, but I can't figure out what it could be.
I ask because I'm currently working out some kinks in my own custom iterator implementations and looking at the STL as a model.
The comment above that complains about std::rel_ops, which provide a template<class T> bool operator!=(const T& lhs, const T& rhs).
Reducing __normal_iterator to it's bare essentials to show the problem, we get this:
#include <utility>
template<typename T>
struct normal_iterator {
T m_base;
const T& base() const { return m_base; }
};
// (1)
template<typename IteratorL, typename IteratorR>
bool operator!=(const normal_iterator<IteratorL>& lhs, const normal_iterator<IteratorR>& rhs) {
return lhs.base() != rhs.base();
}
// (2)
template<typename Iterator>
bool operator!=(const normal_iterator<Iterator>& lhs, const normal_iterator<Iterator>& rhs) {
return lhs.base() != rhs.base();
}
int main() {
using namespace std::rel_ops;
// Your container's `const_iterator` is `const int*`, and `iterator` is `int*`
normal_iterator<const int*> a{nullptr};
normal_iterator<int*> b{nullptr};
a != b; // Uses (1) to compare const_iterator and iterator
a != a; // Uses (2) to compare two iterators
}
Without the second overload, this would not compile since there are two viable functions to call:
std::rel_ops::operator!=<normal_iterator<int*>>(const normal_iterator<int*>&, const normal_iterator<int*>&)
operator!=<int*, int*>(const normal_iterator<int*>&, const normal_iterator<int*>&)
And neither is more specialiased than the other (it is ambiguous)
For std::rel_ops specifically, there is no reason for the extra == overload, but nothing is stopping a user from writing a similar template<typename T> bool operator==(const T&, const T&) in some other namespace.
I wanted to test this very interesting answer and came out with this minimal implementation:
class A
{
enum M { a };
std::tuple<int> members;
public:
A() { std::get<M::a>(members) = 0; }
A(int value) { std::get<M::a>(members) = value; }
A(const A & other) { members = other.members; }
int get() const { return std::get<M::a>(members); }
bool operator==(A & other) { return members == other.members; }
};
and a simple test:
int main() {
A x(42);
A y(x);
std::cout << (x==y) << std::endl;
return 0;
}
Everything's fine, until I define a simple struct B {}; and try to add an instance of it as a member. As soon as I write
std::tuple<int, B> members;
the operator== isn't ok anymore and I get this message from the compiler (gcc 5.4.1):
error: no match for ‘operator==’ (operand types are ‘std::__tuple_element_t<1ul, std::tuple<int, B> > {aka const B}’ and ‘std::__tuple_element_t<1ul, std::tuple<int, B> > {aka const B}’)
return bool(std::get<__i>(__t) == std::get<__i>(__u))
^
I tried providing an operator== to B:
struct B
{
bool operator==(const B &){ return true; }
};
and had an extra from compiler:
candidate: bool B::operator==(const B&) <near match>
bool operator==(const B &){ return true; }
^
Can anyone explain what's wrong with B struct? Is it lacking something, or else?
It's ultimately const correctness. You didn't const qualify B's (or A's, for that matter) comparison operator and its parameter consistently.
Since tuple's operator== accepts by a const reference, it cannot use your const-incorrect implementation. And overload resolution fails as a consequence.
Tidying up all of those const qualifiers resolves all the errors.
I am trying to find vector of a struct within a set. In order to do so I wrote the following code:
#include <cstdlib>
#include <iostream>
#include <set>
#include <vector>
using namespace std;
struct A{
int a;
};
int main(int argc, char** argv) {
std::set< std::vector<A> > aObj;
A a1,a2,a3,a4,a5,a6;
a1.a=5; a2.a=8; a3.a=10;
a4.a=5; a5.a=8; a6.a=10;
vector<A> vecA,vecB;
vecA.push_back(a1); vecA.push_back(a2); vecA.push_back(a3);
aObj.insert(vecA);
set< vector<A> >::iterator it = aObj.find(vecB);
if (it != myset.end()) {
cout<<"\n Found vector B. \n";
}
return 0;
}
However, the above code is giving me the following error:
/usr/include/c++/4.6/bits/stl_algobase.h:881:6: error: no match for ‘operator<’ in ‘* __first1 < * __first2’
/usr/include/c++/4.6/bits/stl_algobase.h:881:6: note: candidates are:
/usr/include/c++/4.6/bits/stl_pair.h:207:5: note: template<class _T1, class _T2> bool std::operator<(const std::pair<_T1, _T2>&, const std::pair<_T1, _T2>&)
/usr/include/c++/4.6/bits/stl_iterator.h:291:5: note: template<class _Iterator> bool std::operator<(const std::reverse_iterator<_Iterator>&, const std::reverse_iterator<_Iterator>&)
/usr/include/c++/4.6/bits/stl_iterator.h:341:5: note: template<class _IteratorL, class _IteratorR> bool std::operator<(const std::reverse_iterator<_IteratorL>&, const std::reverse_iterator<_IteratorR>&)
/usr/include/c++/4.6/bits/basic_string.h:2510:5: note: template<class _CharT, class _Traits, class _Alloc> bool std::operator<(const std::basic_string<_CharT, _Traits, _Alloc>&, const std::basic_string<_CharT, _Traits, _Alloc>&)
/usr/include/c++/4.6/bits/basic_string.h:2522:5: note: template<class _CharT, class _Traits, class _Alloc> bool std::operator<(const std::basic_string<_CharT, _Traits, _Alloc>&, const _CharT*)
/usr/include/c++/4.6/bits/basic_string.h:2534:5: note: template<class _CharT, class _Traits, class _Alloc> bool std::operator<(const _CharT*, const std::basic_string<_CharT, _Traits, _Alloc>&)
The other answer explains it nicely. If A defines a weak total ordering (e.g. by implementing operator<) you'll be able to find the vectors.
Here's how to make the code more succinct:
Live On Coliru
#include <iostream>
#include <set>
#include <vector>
struct A {
int a;
bool operator<(A const &other) const { return a < other.a; }
};
int main() {
std::set<std::vector<A> > myset{
{ { 4 }, { 7 }, { 9 } },
{ { 5 }, { 8 }, { 10 } },
{ { 6 }, { 9 }, { 11 } },
};
auto it = myset.find({ {1}, {2}, {3} });
std::cout << "Found vector: " << std::boolalpha << (it != myset.end()) << "\n";
it = myset.find({ {5}, {8}, {10} });
std::cout << "Found vector: " << std::boolalpha << (it != myset.end()) << "\n";
}
Prints
Found vector: false
Found vector: true
This uses aggregate initialization for A and uniform initialization of the vector and set containers ({a,b,c} will use the std::initialializer_list<> constructor overloads)
As it is now, std::set::find is trying to compare the given vector with the vector in the set using std::less<std::vector<A>>, which is the default comparator for instances of std::set<std::vector<A>>. AFAIK, std::less will call bool operator<(const std::vector<A>& lhs, const std::vector<A>& rhs) const to compare the vectors, and this will in turn perform a lexicographical comparison of the vectors by using std::less<A>. std::less<A> will then try to call either bool A::operator<(const A& rhs) const (member function version) or bool operator<(const A& lhs, const A& rhs) const (free function version) to compare instances of A. This fails because neither of these functions exist.
You have two options:
1) You equip your struct A with a comparison operator (in this example, we do it as a member function) like so:
bool operator<(const A& rhs) const { return a < rhs.a; }
and rely on std::vector's implementation of operator<, which performs lexicographical comparison. Lexicographical comparison means that the vector elements are compared pairwise until a pair (x,y) of elements of the two vectors being compared is found where x < y or y < x. If no such pair exists, then both vectors are consider equal, unless they have different lengths, in which case the shorter vector is a prefix of the longer one, and is consider less.
2) You provide a comparator to your std::set that can compare the vectors, specifically, determine which of two vectors is less than the other. This is only useful if you don't want to use std::vector's lexicographical comparison and if you can define a weak total order on your vectors. If that is the case, then you can implement a comparator like so:
struct VecCmp {
bool operator<(const std::vector<A>& lhs, const std::vector<A>& rhs) const {
// determine whether lhs is less than rhs and return true if so, false otherwise
}
};
You then configure your std::set to use this comparator like so:
std::set<std::vector<A>, VecCmp> myset(VecCmp());
I am trying to use blitz++ arrays, since I understand they generally offer higher performance than other forms of arrays. Is it possible to use blitz++ arrays as keys in a map? Trying
#include <map>
#include <blitz/array.h>
using namespace std;
map<blitz::Array<int,1>,int> testmap;
blitz::Array<int,1> B(3);
B = 1,2,3;
testmap.insert(make_pair(B,2));
does not compile. Here's the error:
In file included from /usr/include/c++/4.6/string:50:0,
/usr/include/c++/4.6/bits/stl_function.h: In member function ‘bool
std::less<_Tp>::operator()(const _Tp&, const _Tp&) const [with _Tp =
blitz::Array]’:
/usr/include/c++/4.6/bits/stl_function.h:236:22: error: cannot convert
‘blitz::BzBinaryExprResult,
blitz::Array >::T_result {aka
blitz::_bz_ArrayExpr, blitz::FastArrayIterator, blitz::Less > >}’ to
‘bool’ in return
Is this a matter of requiring a definition of the < operator, and if so, can/should I define it myself?
ANSWER
As suggested by Jimmy Thompson, a possible solution is to define:
struct MyComparison
{
bool operator() (const blitz::Array<int, 1> &lhs, const blitz::Array<int, 1> &rhs) const
{
if (lhs.size() < rhs.size()) {return true;}
else if (lhs.size() > rhs.size()) {return false;}
else
{
for (int i=0; i<lhs.size(); i++)
{
if (lhs(i)<rhs(i)) {return true;}
else if(lhs(i)>rhs(i)) {return false;}
}
}
}
};
Then
map<blitz::Array<int,1>,int, MyComparison> testmap;
The std::map documentation states that keys are compared using std::less by default. This just calls < and expects a return of true or false.
In order for you to use Blitz arrays as a key, you need to do one of the following:
Create your own comparison function, like std::less, which returns a boolean value stating whether one Blitz array is 'less' than the other (how you choose to determine this is up to you). Assuming you made this function and called it MyComparison, you would then create your map as follows map<blitz::Array<int,1>, int, MyComparison> testmap;.
struct MyComparison
{
bool operator() (const blitz::Array<int, 1> &lhs, const blitz::Array<int, 1> &rhs) const
{
// Blitz array comparison
}
};
Wrap your Blitz array type (blitz::Array<int,1>) in another object, overloading the < operator for that given object and then performing your comparison in there. For example:
class MyArrayWrapper
{
blitz::Array<int, 1> contents;
public:
// Constructor, etc.
bool operator<(const MyArrayWrapper &rhs) const
{
// Blitz array comparison
}
};
Then in your current file.
std::map<MyArrayWrapper,int> testmap;
I have a std::set container whose elements are objects of the following class:
class LaneConnector {
public:
const Lane* getLaneFrom() const {
return From;
}
const Lane* getLaneTo() const {
return To;
}
private:
Lane* From;
Lane* To;
}
and my comparator function is as follows:
struct MyLaneConectorSorter {
bool operator() (LaneConnector * c, LaneConnector * d)
{
Lane* a = const_cast<Lane*>(c->getLaneFrom());
Lane* b = const_cast<Lane*>(d->getLaneFrom());
return (a->getLaneID() < b->getLaneID());
}
} myLaneConnectorSorter;
Now when I try to sort the elements in the set with:
//dont panic, the container just came through a const_iterator of a std::map :)
const std::set<LaneConnector*> & tempLC = (*it_cnn).second;
std::sort(tempLC.begin(), tempLC.end(), myLaneConnectorSorter);
I get a frenzy of errors starting with the following lines, Appreciate if you help me solve this problem.
Thanks:
/usr/include/c++/4.6/bits/stl_algo.h: In function ‘void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = std::_Rb_tree_const_iterator<LaneConnector*>, _Compare = {anonymous}::MyLaneConectorSorter]’:
/home/.../dev/Basic/shared/conf/simpleconf.cpp:1104:65: instantiated from here
/usr/include/c++/4.6/bits/stl_algo.h:5368:4: error: no match for ‘operator-’ in ‘__last - __first’
/usr/include/c++/4.6/bits/stl_algo.h:5368:4: note: candidates are:
/usr/include/c++/4.6/bits/stl_iterator.h:321:5: note: template<class _Iterator> typename std::reverse_iterator::difference_type std::operator-(const std::reverse_iterator<_Iterator>&, const std::reverse_iterator<_Iterator>&)
/usr/include/c++/4.6/bits/stl_iterator.h:378:5: note: template<class _IteratorL, class _IteratorR> typename std::reverse_iterator<_IteratorL>::difference_type std::operator-(const std::reverse_iterator<_IteratorL>&, const std::reverse_iterator<_IteratorR>&)
/usr/include/c++/4.6/bits/stl_bvector.h:181:3: note: std::ptrdiff_t std::operator-(const std::_Bit_iterator_base&, const std::_Bit_iterator_base&)
/usr/include/c++/4.6/bits/stl_bvector.h:181:3: note: no known conversion for argument 1 from ‘std::_Rb_tree_const_iterator<LaneConnector*>’ to ‘const std::_Bit_iterator_base&’
First, you cannot sort an std::set. It is a sorted structure, sorting happens upon construction or insertion.
Second, you can construct an std::set with your own sorting functor, and you can avoid unnecessary const_casts by making it take const pointers:
struct MyLaneConectorSorter {
bool operator() (const LaneConnector* lhs, const LaneConnector* rhs) const
{
// you may want to put some null pointer checks in here
const Lane* a = lhs->getLaneFrom();
const Lane* b = rhs->getLaneFrom();
return a->getLaneID() < b->getLaneID();
}
};
and instantiate the set like this:
std::set<LaneConnector*, MyLaneConectorSorter> s(MyLaneConectorSorter());
or, if you want to construct it from a different set, with a different ordering,
std::set<LaneConnector*> orig = ..... ;
....
std::set<LaneConnector*, MyLaneConectorSorter> s(orig.begin(), orig.end(), MyLaneConectorSorter());