Is it possible to overload operator "..." in C++? - c++

#include <iostream>
#include <vector>
using namespace std;
//
// Below is what I want but not legal in current C++!
//
vector<int> operator ...(int first, int last)
{
vector<int> coll;
for (int i = first; i <= last; ++i)
{
coll.push_back(i);
}
return coll;
}
int main()
{
for (auto i : 1...4)
{
cout << i << endl;
}
}
I want to generate an integer sequence by using syntax 1...100, 7...13, 2...200 and the like.
I want to overload ... in C++.
Is it possible?

Is it possible?
No, it isn't possible.
... isn't an operator but a placeholder for variadic arguments.

There is no ... operator in C++, so you can't overload it.
However, you can use an ordinary name such as range.
Assuming a header that defines a suitable range function, your intended program
int main()
{
for (auto i : 1...4)
{
cout << i << endl;
}
}
… can then look like this:
#include <p/expressive/library_extension.hpp>
using progrock::expressive::range;
#include <iostream>
#include <vector>
using namespace std;
int main()
{
for( auto i : range( 1, 4 ) )
{
cout << i << endl;
}
}
This is actual working code using the Expressive C++ library's range
implementation. However, that
library is currently in its very infant stages, in flux, with all kinds of
imperfections and fundamental changes daily. Also it implements an extended
dialect of C++, that is as yet unfamiliar to all but myself, so that posting the range implementation here where pure C++ is expected, would possibly/probably provoke negative reactions; I'm sorry. But you can easily translate that implementation to raw C++. It's Boost 1.0 license.

As mentioned in the other answers this is not possible since ... is not a valid operator, but in this language you can always create weird idioms like this:
#include <iostream>
struct int_it
{
int_it (int l, int r): left(l), right(r){}
void operator++() { left++;}
bool operator!=(const int_it& rhs) { return left != rhs.right;}
int operator*(){ return left;};
int left;
int right;
};
class range_op
{
public:
static range_op op() { return {0,0}; }
operator int() { return right - left; }
auto begin(){ return int_it{left, right}; }
auto end(){ return int_it{right,right}; }
private:
range_op(int l, int r): left(l), right(r){}
int left;
int right;
friend range_op operator*(int lhs, range_op r);
friend range_op operator*(range_op r, int rhs);
};
range_op operator*(int lhs, range_op r)
{
return range_op{lhs, r.right};
}
range_op operator*(range_op d, int rhs)
{
return range_op{d.left, rhs};
}
const auto o = range_op::op();
int main() {
for (int i : 2*o*6)
{
std::cout << i << std::endl;
}
return 0;
}
This is just a quick example, so no range checks and a lot of bugs.

Related

how to create an overload operator for adding a new element to the beginning or end of a vector с++

First I would like to apologize for the quality of my code, I'm just learning.
I have a university assignment.
String concatenation and adding one character to a string (like
on the left and on the right). Implement using overloading
the operator.
The question is this:
I need to implement two overloads (operator+)
First: adding one element to the end of the vector ( + 'e', ​​for example ).
Second: adding an element to the beginning of the vector ('e' + , for example).
I have problems in order to implement the second part of the assignment.
I searched similar questions on stackoverflow, but they did not help me much.
Here is my code:
#include <iostream>
#include <vector>
using namespace std;
template <class T>
class String
{
private:
public:
vector<T> ptr_string;
String() // default value constructor (empty string)
{
ptr_string.push_back('\0');
}
String(const String& other) // copy constructor of the same type
{
int n = other.getLength();
for (int i = 0; i < n; i++)
{
ptr_string.push_back(other.ptr_string[i]);
}
}
String(T symbol, int n) // n times repeated value constructor
{
for (int i = 0; i < n; i++)
{
ptr_string.push_back(symbol);
}
}
String(String&& a) // move constructor
: ptr_string(a.ptr_string)
{
a.ptr_string = nullptr;
}
int getLength() const
{
return ptr_string.size();
}
void printString() const
{
int i = 0;
for (int i = 0; i < ptr_string.size(); i++)
{
cout << ptr_string[i];
}
cout << endl;
}
template <typename T2>
auto operator+(T2 b)
{
ptr_string.push_back(b);
return ptr_string;
}
auto operator+(String const& a)
{
ptr_string.push_back(a);
return ptr_string;
}
};
int main()
{
String<char> P = String<char>('P', 10);
P + 'e';
P.printString();
'e' + P;
P.printString();
}
I tried to pass a reference to a vector as a parameter, but I ran into a problem that this is most likely not the right solution.
auto operator+( String const& a)
{
ptr_string.push_back(a);
return ptr_string;
}
String<char> P = String<char>( 'P', 10);
'e' + P;
P.printString();
expected result: ePPPPPPPPPP
First, operator+ should not modify the current object. It should not return a vector but a new String<T>. It should be const.
Your char,int constuctor misses to add a nullterminator. Maybe that was on purpose, but I changed it because I am using that constructor. Moreover, I removed the move constructor, because its not needed yet. In its implementation you assign nullptr to the vector which is wrong. You need not implement the move constructor, you can declare it as =default;. This is what I also did for the copy constructor, because the compiler generated copy constructor is as good (or better) than your self written one.
Then, there is no + for 'e'+String in your code. When implmented as member then this is always the left operand. You can implement it as free function.
#include <iostream>
#include <vector>
template<class T>
class String {
public:
std::vector<T> ptr_string;
String() { ptr_string.push_back('\0'); }
String(const String& other) = default;
String(T symbol, int n) {
for (int i = 0; i < n; i++) {
ptr_string.push_back(symbol);
}
ptr_string.push_back('\0');
}
int getLength() const {
return ptr_string.size();
}
void printString() const {
int i = 0;
for (int i = 0; i < ptr_string.size(); i++) {
std::cout << ptr_string[i];
}
std::cout << std::endl;
}
template<typename T2>
auto operator+( T2 b) const {
String res = *this;
res.ptr_string.push_back(b);
return res;
}
auto operator+( String const& a) {
String res = *this;
for (const auto& c : a.ptr_string) res.ptr_string.push_back(c);
return res;
}
};
template<typename T2,typename T>
auto operator+(const T2& b,const String<T>& a) {
return String<T>(b,1) + a;
}
int main() {
String<char> P = String<char>( 'P', 10);
auto Y = P + 'e';
P.printString();
Y.printString();
auto Z = 'e' + P;
P.printString();
Z.printString();
}
Demo
This is just minimum changes on your code. I would actually implement also the other operators outside of the class as free functions. The loop in the char,int constructor should be replaced with the appropriate vector constructor and perhaps there is more which can be improved. For more on operator overloading I refer you to https://en.cppreference.com/w/cpp/language/operators and What are the basic rules and idioms for operator overloading?
I don't think your assignment really cover a scenario that happens in real life. It is full of code smell. As #463035818_is_not_a_number mentionned operator+ usually don't modify the current object. But it is technically possible, See below. Vector are not meant to "push_front", avoid 'push_front' on vector as a general rule (here, i use deque for ex).
#include <deque>
#include <iostream>
#include <string>
template<class T>
struct ConcatenableDeq
{
std::deque<T> _deq;
ConcatenableDeq(std::deque<T> deq) : _deq(deq) {};
void print() const
{
for (const auto& e : this->_deq)
std::cout << e << " ";
std::cout << std::endl;
}
friend void operator+(ConcatenableDeq<T>& cd, const T& v)
{
cd._deq.push_back(v);
}
friend void operator+(const T& v, ConcatenableDeq<T>& cd)
{
cd._deq.push_front(v);
}
};
int main(int argc, char* argv[])
{
ConcatenableDeq<char> cd({ '1', '2', '3' });
cd.print();
cd + '4';
cd.print();
'0' + cd;
cd.print();
// output:
// 1 2 3
// 1 2 3 4
// 0 1 2 3 4
}

C++ iterate over members of struct

Say I have a struct:
struct Boundary {
int top;
int left;
int bottom;
int right;
}
and a vector
std::vector<Boundary> boundaries;
What would be the most C++ style way to access the structs to get the sum of top, left, bottom and right separately?
I could write a loop like
for (auto boundary: boundaries) {
sum_top+=boundary.top;
sum_bottom+=boundary.bottom;
...
}
This seems like a lot of repetition. Of course I could do this instead:
std::vector<std::vector<int>> boundaries;
for (auto boundary: boundaries) {
for(size_t i=0; i<boundary.size();i++) {
sums.at(i)+=boundary.at(i)
}
}
But then I'd loose all the meaningful struct member names. Is there a way so that I can write a something like the following function:
sum_top=make_sum(boundaries,"top");
Reflection does not seem to be an option in C++. I am open to use C++ up to Version 14.
std::accumulate(boundaries.begin(), boundaries.end(), 0,
[](Boundary const & a, Boundary const & b) { return a.top + b.top); });
(IIRC the Boundary const &'s can be auto'd in C++17)
This doesn't make it generic for the particular element, which - indeed, due to the lack of reflection - isn't easy to generalize.
There are a few ways to ease your pain, though;
You could use a pointer-to-member, which is fine for your szenario but not very c-plusplus-y:
int Sum(vector<Boundary>const & v, int Boundary::*pMember)
{
return std::accumulate( /*...*/,
[&](Boundary const & a, Boundary const & b)
{
return a.*pMember + b.*pMember;
});
}
int topSum = Sum(boundaries, &Boundary::top);
(For pointer-to-member, see e.g. here: Pointer to class data member "::*")
You could also make this generic (any container, any member type), and you could also replace the pointer-to-member with a lambda (also allowing member functions)
You can achieve the desired effect with Boost Hana reflection:
#include <iostream>
#include <vector>
#include <boost/hana.hpp>
struct Boundary {
BOOST_HANA_DEFINE_STRUCT(Boundary,
(int, top),
(int, left),
(int, bottom),
(int, right)
);
};
template<class C, class Name>
int make_sum(C const& c, Name name) {
int sum = 0;
for(auto const& elem : c) {
auto& member = boost::hana::at_key(elem, name);
sum += member;
}
return sum;
}
int main() {
std::vector<Boundary> v{{0,0,1,1}, {1,1,2,2}};
std::cout << make_sum(v, BOOST_HANA_STRING("top")) << '\n';
std::cout << make_sum(v, BOOST_HANA_STRING("bottom")) << '\n';
}
See Introspecting user-defined types for more details.
I am probably a bit late to the party, but I wanted to add answer inspired by the one of #TobiasRibizel. Instead of adding much boilerplate code to your struct we add more boilerplate code once in the form of an iterator over (specified) members of a struct.
#include <iostream>
#include <string>
#include <map>
template<class C, typename T, T C::* ...members>
class struct_it {
public:
using difference_type = std::ptrdiff_t;
using value_type = T;
using pointer = T*;
using reference = T&;
using iterator_category = std::bidirectional_iterator_tag;
constexpr struct_it (C &c) : _index{0}, _c(c)
{}
constexpr struct_it (size_t index, C &c) : _index{index}, _c(c)
{}
constexpr static struct_it make_end(C &c) {
return struct_it(sizeof...(members), c);
}
constexpr bool operator==(const struct_it& other) const {
return other._index == _index; // Does not check for other._c == _c, since that is not always possible. Maybe do &other._c == &_c?
}
constexpr bool operator!=(const struct_it& other) const {
return !(other == *this);
}
constexpr T& operator*() const {
return _c.*_members[_index];
}
constexpr T* operator->() const {
return &(_c.*_members[_index]);
}
constexpr struct_it& operator--() {
--_index;
return *this;
}
constexpr struct_it& operator--(int) {
auto copy = *this;
--_index;
return copy;
}
constexpr struct_it& operator++() {
++_index;
return *this;
}
constexpr struct_it& operator++(int) {
auto copy = *this;
++_index;
return copy;
}
private:
size_t _index;
C &_c;
std::array<T C::*, sizeof...(members)> _members = {members...}; // Make constexpr static on C++17
};
template<class C, typename T, T C::* ...members>
using cstruct_it = struct_it<const C, T, members...>;
struct boundary {
int top;
int bottom;
int left;
int right;
using iter = struct_it<boundary, int, &boundary::top, &boundary::bottom, &boundary::left, &boundary::right>;
using citer = cstruct_it<boundary, int, &boundary::top, &boundary::bottom, &boundary::left, &boundary::right>;
iter begin() {
return iter{*this};
}
iter end() {
return iter::make_end(*this);
}
citer cbegin() const {
return citer{*this};
}
citer cend() const {
return citer::make_end(*this);
}
};
int main() {
boundary b{1,2,3,4};
for(auto i: b) {
std::cout << i << ' '; // Prints 1 2 3 4
}
std::cout << '\n';
}
It works on C++14, on C++11 the constexpr functions are all const by default so they don't work, but just getting rid of the constexpr should do the trick. The nice thing is that you can choose just some members of your struct and iterate over them. If you have the same few members that you will always iterate over, you can just add a using. That is why I chose to make the pointer-to-members part of the template, even if it is actually not necessary, since I think that only the iterators over the same members should be of the same type.
One could also leave that be, replace the std::array by an std::vector and choose at runtime over which members to iterate.
Without going too much into the memory layout of C++ objects, I would propose replacing the members by 'reference-getters', which adds some boilerplate code to the struct, but except for replacing top by top() doesn't require any changes in the way you use the struct members.
struct Boundary {
std::array<int, 4> coordinates;
int& top() { return coordinates[0]; }
const int& top() const { return coordinates[0]; }
// ...
}
Boundary sum{};
for (auto b : boundaries) {
for (auto i = 0; i < 4; ++i) {
sum.coordinates[i] += b.coordinates[i];
}
}

How to compare two objects using templates?

I want to compare two objects and get larger among them using templates. Passing the object as an argument isn't working as the code below. See the sample code given below. That's what I'm trying to do.
#include <iostream>
using namespace std;
template <class T>
class max
{
T a;
public:
max(T a)
{
this.a = a;
}
T Large(T n2)
{
return (a > n2.a) ? a : n2.a;
}
};
int main()
{
max <int> obj1(10);
max <int> obj2(20);
cout<<obj1.Large(obj2)<<" is larger"<<endl;
return 0;
}
I'm doing something like this but by comparing 2 objects.
// class templates
#include <iostream>
using namespace std;
template <class T>
class mypair {
T a, b;
public:
mypair (T first, T second)
{a=first; b=second;}
T getmax ();
};
template <class T>
T mypair<T>::getmax ()
{
T retval;
retval = a>b? a : b;
return retval;
}
int main () {
mypair <int> myobject (100, 75);
cout << myobject.getmax();
return 0;
}
This code seems to work fine, let me know if this helps
#include <iostream>
using namespace std;
template <class T>
class Maxi {
T a;
public:
Maxi(T val)
{
this->a = val;
}
T Large(maxi n2)
{
return (a > n2.a) ? a : n2.a;
}
};
int main() {
Maxi <int> obj_1(10);
Maxi <int> obj_2(20);
cout<<obj_1.Large(obj_2)<<" is larger"<<endl;
return 0;
}
There is already a max and min template function provided under algorithm.
Just call std::max(10, 20) to get the larger between the two.
You can even provide your own comparator for custom comparison.
Side note: It seems like by including iostream, you can use max and min without algorithm.
Problems I see:
Use of
using namespace std;
is probably going to mess things up for you since std::max gets pulled into the mix indirectly. It does for me with g++. Don't use it.
Syntax error in the following line:
this.a = a;
That needs to be
this->a = a;
Argument to Large needs to be of type max, not T.
For good measure, I would also make it a const member function.
T Large(max n2) const
{
return (a > n2.a) ? a : n2.a;
}
Use std::cout and std::endl since using namespace std; is problematic.
Here's an updated version of your code with the above fixes:
#include <iostream>
template <class T>
class max
{
private:
T a;
public:
max(T a)
{
this->a = a;
}
T Large(max n2) const
{
return (a > n2.a) ? a : n2.a;
}
};
int main()
{
max <int> obj1(10);
max <int> obj2(20);
std::cout << obj1.Large(obj2) << " is larger"<<std::endl;
return 0;
}
It works for me and produces the following output:
20 is larger
I think you're trying to do this:
template <typename T>
T max(const T &a, const T &b)
{ return (b < a) ? a : b; }
That's how you do that. Your weird mishmash of a class doesn't make any sense at all. And so if I got what you're trying to do wrong, please explain yourself better.
Templates don't have to be classes you know. You can have templated functions.
If you absolutely must use a class, do this then:
template <typename T>
class max
{
T operator ()(const T &a, const T &b) { return (b < a) ? a : b; }
};
int main()
{
max<int> foo;
cout << foo(10, 20) << " is larger\n"; // Don't use endl most of the time.
return 0;
}
Suppose you have two objects that aren't ints, what do you do? Well, you do this:
#include <iostream>
#include <algorithm>
struct A {
int v1;
int v2;
};
bool operator <(A &a, A &b)
{
return (a.v1 < b.v1) || ((a.v1 == b.v1) && (a.v2 < b.v2));
}
::std::ostream &operator <<(::std::ostream &os, const A &a)
{
os << "{" << a.v1 << ", " << a.v2 << "}";
}
int main()
{
A first{10, 20};
B second{20, 10};
::std::cout << ::std::max(first, second) << " is the larger.\n";
}
If you don't want to have to define operator <, then do this:
bool my_less_than(const A &a, const A &b)
{
return (a.v1 < b.v1) || ((a.v1 == b.v1) && (a.v2 < b.v2));
}
int main()
{
A first{10, 20};
B second{20, 10};
::std::cout << ::std::max(first, second, my_less_than) << " is the larger.\n";
}

Is there a range class in C++11 for use with range based for loops?

I found myself writing this just a bit ago:
template <long int T_begin, long int T_end>
class range_class {
public:
class iterator {
friend class range_class;
public:
long int operator *() const { return i_; }
const iterator &operator ++() { ++i_; return *this; }
iterator operator ++(int) { iterator copy(*this); ++i_; return copy; }
bool operator ==(const iterator &other) const { return i_ == other.i_; }
bool operator !=(const iterator &other) const { return i_ != other.i_; }
protected:
iterator(long int start) : i_ (start) { }
private:
unsigned long i_;
};
iterator begin() const { return iterator(T_begin); }
iterator end() const { return iterator(T_end); }
};
template <long int T_begin, long int T_end>
const range_class<T_begin, T_end>
range()
{
return range_class<T_begin, T_end>();
}
And this allows me to write things like this:
for (auto i: range<0, 10>()) {
// stuff with i
}
Now, I know what I wrote is maybe not the best code. And maybe there's a way to make it more flexible and useful. But it seems to me like something like this should've been made part of the standard.
So is it? Was some sort of new library added for iterators over a range of integers, or maybe a generic range of computed scalar values?
The C++ standard library does not have one, but Boost.Range has boost::counting_range, which certainly qualifies. You could also use boost::irange, which is a bit more focused in scope.
C++20's range library will allow you to do this via view::iota(start, end).
As far as I know, there is no such class in C++11.
Anyway, I tried to improve your implementation. I made it non-template, as I don't see any advantage in making it template. On the contrary, it has one major disadvantage : that you cannot create the range at runtime, as you need to know the template arguments at compile time itself.
//your version
auto x = range<m,n>(); //m and n must be known at compile time
//my version
auto x = range(m,n); //m and n may be known at runtime as well!
Here is the code:
class range {
public:
class iterator {
friend class range;
public:
long int operator *() const { return i_; }
const iterator &operator ++() { ++i_; return *this; }
iterator operator ++(int) { iterator copy(*this); ++i_; return copy; }
bool operator ==(const iterator &other) const { return i_ == other.i_; }
bool operator !=(const iterator &other) const { return i_ != other.i_; }
protected:
iterator(long int start) : i_ (start) { }
private:
unsigned long i_;
};
iterator begin() const { return begin_; }
iterator end() const { return end_; }
range(long int begin, long int end) : begin_(begin), end_(end) {}
private:
iterator begin_;
iterator end_;
};
Test code:
int main() {
int m, n;
std::istringstream in("10 20");
if ( in >> m >> n ) //using in, because std::cin cannot be used at coliru.
{
if ( m > n ) std::swap(m,n);
for (auto i : range(m,n))
{
std::cout << i << " ";
}
}
else
std::cout <<"invalid input";
}
Output:
10 11 12 13 14 15 16 17 18 19
Onine demo.
I wrote a library called range for exactly the same purpose except it is a run-time range, and the idea in my case came from Python. I considered a compile-time version, but in my humble opinion there is no real advantage to gain out the compile-time version. You can find the library on bitbucket, and it is under Boost License: Range. It is a one-header library, compatible with C++03 and works like charm with range-based for loops in C++11 :)
Features:
A true random access container with all the bells and whistles!
Ranges can be compared lexicographically.
Two functions exist(returns
bool), and find(returns iterator) to check the existence of a number.
The library is unit-tested using CATCH.
Examples of basic
usage, working with standard containers, working with standard
algorithms and working with range based for loops.
Here is a one-minute introduction. Finally, I welcome any suggestion about this tiny library.
I found that boost::irange was much slower than the canonical integer loop. So I settled on the following much simpler solution using a preprocessor macro:
#define RANGE(a, b) unsigned a=0; a<b; a++
Then you can loop like this:
for(RANGE(i, n)) {
// code here
}
This range automatically starts from zero. It could be easily extended to start from a given number.
Here is a simpler form which is working nicely for me. Are there any risks in my approach?
r_iterator is a type which behaves, as much as possible, like a long int. Therefore many operators such as == and ++, simply pass through to the long int. I 'expose' the underlying long int via the operator long int and operator long int & conversions.
#include <iostream>
using namespace std;
struct r_iterator {
long int value;
r_iterator(long int _v) : value(_v) {}
operator long int () const { return value; }
operator long int& () { return value; }
long int operator* () const { return value; }
};
template <long int _begin, long int _end>
struct range {
static r_iterator begin() {return _begin;}
static r_iterator end () {return _end;}
};
int main() {
for(auto i: range<0,10>()) { cout << i << endl; }
return 0;
}
(Edit: - we can make the methods of range static instead of const.)
This might be a little late but I just saw this question and I've been using this class for a while now :
#include <iostream>
#include <utility>
#include <stdexcept>
template<typename T, bool reverse = false> struct Range final {
struct Iterator final{
T value;
Iterator(const T & v) : value(v) {}
const Iterator & operator++() { reverse ? --value : ++value; return *this; }
bool operator!=(const Iterator & o) { return o.value != value; }
T operator*() const { return value; }
};
T begin_, end_;
Range(const T & b, const T & e) : begin_(b), end_(e) {
if(b > e) throw std::out_of_range("begin > end");
}
Iterator begin() const { return reverse ? end_ -1 : begin_; }
Iterator end() const { return reverse ? begin_ - 1: end_; }
Range() = delete;
Range(const Range &) = delete;
};
using UIntRange = Range<unsigned, false>;
using RUIntRange = Range<unsigned, true>;
Usage :
int main() {
std::cout << "Reverse : ";
for(auto i : RUIntRange(0, 10)) std::cout << i << ' ';
std::cout << std::endl << "Normal : ";
for(auto i : UIntRange(0u, 10u)) std::cout << i << ' ';
std::cout << std::endl;
}
have you tried using
template <class InputIterator, class Function>
Function for_each (InputIterator first, InputIterator last, Function f);
Most of the time fits the bill.
E.g.
template<class T> void printInt(T i) {cout<<i<<endl;}
void test()
{
int arr[] = {1,5,7};
vector v(arr,arr+3);
for_each(v.begin(),v.end(),printInt);
}
Note that printInt can OFC be replaced with a lambda in C++0x.
Also one more small variation of this usage could be (strictly for random_iterator)
for_each(v.begin()+5,v.begin()+10,printInt);
For Fwd only iterator
for_each(advance(v.begin(),5),advance(v.begin(),10),printInt);
You can easily generate an increasing sequence in C++11 using std::iota():
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>
template<typename T>
std::vector<T> range(T start, T end)
{
std::vector<T> r(end+1-start, T(0));
std::iota(r.begin(), r.end(), T(start));//increasing sequence
return r;
}
int main(int argc, const char * argv[])
{
for(auto i:range<int>(-3,5))
std::cout<<i<<std::endl;
return 0;
}

Need help with STL sort algorithm

I'm having some troubles with using the std::sort algorithm here. I was reading that you can just overload the less than operator to sort classes, but I have been getting all sorts of errors. I have also tried using a functor as you can see in the example I made below.
I was hoping somebody could see what I'm doing wrong here.
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdlib.h>
#include <time.h>
class Thing {
public:
Thing(int val) {
this->_val = val;
}
bool operator<(Thing& rhs) {
std::cout << "this works!";
return this->val() < rhs.val();
}
int val() {
return this->_val;
}
protected:
int _val;
};
struct Sort {
bool operator()(Thing& start, Thing& end) {
return start.val() < end.val();
}
};
int main (int argc, char * const argv[]) {
std::srand(std::time(NULL));
std::vector<Thing> things;
for(int i = 0; i < 100; i++) {
Thing myThing(std::rand());
things.push_back(myThing);
}
if(things[1] < things[2]) {
//This works
}
//std::sort(things.begin(), things.end()); //This doesn't
//std::sort(things.begin(), things.end(), Sort()); //Neither does this
for(int i = 0; i < 100; i++) {
std::cout << things.at(i).val() << std::endl;
}
return 0;
}
Make your val() and operator<() const functions.
The same for Sort::operator() — take const Thing& instead of Thing&.
I believe you need to change
bool operator()(Thing& start, Thing& end) {
into
bool operator()(const Thing& start, const Thing& end) {
and
int val() {
into
int val() const {
IOW, your code needs to be const-correct and not claim it may modify things it in fact doesn't (nor needs to).
Try making operator< take its argument by const reference. You'll need to change its implementation to directly access _val or (preferably) make val() const as well when you do this (because a const member function can't call a non-const one).