-4

This isn't a duplicate. I don't want to compare strings and the possible duplicate contains much to much information.

Is there a function compareTo in C++ like in Java?

int compareTo(T o)

Parameters: o - the object to be compared.

Returns: a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

-- Documentation

user1
  • 404
  • 1
  • 5
  • 18
  • 3
    Possible duplicate of [Is there a CompareTo method in C++ similar to Java where you can use > < = operations on a data type](https://stackoverflow.com/questions/20005392/is-there-a-compareto-method-in-c-similar-to-java-where-you-can-use-opera) – Valentino Mar 22 '19 at 19:14
  • 4
    There will be a [default comparison operator (`operator<=>`)](https://en.cppreference.com/w/cpp/language/operator_comparison#Three-way_comparison) in the next version of c++. – François Andrieux Mar 22 '19 at 19:15
  • 2
    @FrançoisAndrieux I think you should add this comment as an answer to the linked question. And/Or add it as an answer here. (I find that the linked question contains too much details. And the question is about strings explicitly, whereas I want to compare (vectors of) ints) – user1 Mar 22 '19 at 19:25
  • Are you looking for [std::basic_string::compare](https://en.cppreference.com/w/cpp/string/basic_string/compare)? – Jesper Juhl Mar 22 '19 at 20:20
  • @JesperJuhl I do **not** want to compare strings – user1 Mar 23 '19 at 01:44

1 Answers1

2

Not until C++20's "spaceship operator" <=>, but you could easily define one:

template<typename T, typename U>
constexpr int compareTo(const T &a, const U &b)
{
    if (a < b) return -1;
    else if (a == b) return 0;
    else return 1;
}

This does of course assume types T and U have well-behaving comparison operators (no tricks).

Cruz Jean
  • 2,761
  • 12
  • 16
  • Haha, space ship operator... Where does this interesting nickname come from? – con ko Mar 23 '19 at 02:30
  • 1
    @Constructor You know, I never thought to look it up, but [wikipedia](https://en.wikipedia.org/wiki/Three-way_comparison#Trivia) says it was because it looked like a ship from a text-based Star Trek game. – Cruz Jean Mar 24 '19 at 17:59