4

I'm writing a simple C++17 program that compares two vectors of integers.

e.g., I have two vectors: a represents the number -1, b 25

std::vector<int> a = {-1};
std::vector<int> b = {2, 5};
if(a < b)       std::cout << "a < b" << std::endl;
else if(a > b)  std::cout << "a > b" << std::endl;
else            std::cout << "a = b" << std::endl;

The output produced by the previous piece of code is a < b, and it is correct. Let us consider now the following example:

std::vector<int> a = {-1, 9};
std::vector<int> b = {-1, 9, 9};
if(a < b)       std::cout << "a < b" << std::endl;
else if(a > b)  std::cout << "a > b" << std::endl;
else            std::cout << "a = b" << std::endl;

Here the output is a < b as well, but since -19 > -199 I would like it to be a > b.

There is a way to solve this? For example, I thought of converting the two vectors into integers and comparing them, but I can't figure out how to do that.

Tamfub
  • 43
  • 4
  • 2
    using `<` with vectors will do a lexicographic comparison. Not a numeric comparison. https://en.cppreference.com/w/cpp/container/vector/operator_cmp And because "-19" is lexicographically less than "-199", well... you'll see the results you are getting. – MPops May 29 '19 at 20:49
  • Ok, the lexicographic comparison is not the desired action then. Is there another way to do what I want? – Tamfub May 29 '19 at 20:55
  • Yes. Do the comparison manually (transform vector into integer, then compare?) – MPops May 29 '19 at 20:57

1 Answers1

2

As @MPops commented, using the overloaded operator < with std::vector will do a lexicographical comparison, which is not what you want (a numerical comparison).

Read more in the reference.

You need to do the numerical comparison of two vectors manually, by converting the vector<int> to an int, like this:

#include <iostream>
#include <vector>

template <typename T> int sgn(T val) {
    return (T(0) < val) - (val < T(0));
}

int vectorToInt(std::vector<int> v) {
  int result = 0;
  if(!v.size()) return result;
  result = result * 10 + v[0];
  for (size_t i = 1; i < v.size(); ++i) {
    result = result * 10 + (v[i] * sgn(v[0]));
  }
  return result;
}

int main(void) {
  std::vector<int> a_vec = {-1, 9};
  int a = vectorToInt(a_vec);
  std::vector<int> b_vec = {-1, 9, 9};
  int b = vectorToInt(b_vec);
  std::cout << "Comparing " << a << " with " << b << std::endl;

  if(a < b)       std::cout << "a < b" << std::endl;
  else if(a > b)  std::cout << "a > b" << std::endl;
  else            std::cout << "a = b" << std::endl;
  return 0;
}

Output:

Comparing -19 with -199
a > b
gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • You are welcome @Tambuf, and also welcome to Stack Overflow! I included a full working example, have fun! – gsamaras May 29 '19 at 21:26