Search code examples
c++maxmin

C++ std::max acting like std::min


Note: This is for the problem teleportation from usaco.org (hence the strange variable names, I'm obviously not making an actual teleporter)

When I try using the built-in max for (2, 8), and I get 2 for some reason. I also created my own functions like this:

#define min(number_1, number_2) (number_1 < number_2 ? number_1 : number_2)
#define max(number_1, number_2) (number_1 < number_2 ? number_2 : number_1)

but it still fails. Here is the code:

#include <iostream>
#include <string>

using namespace std;

#define min(number_1, number_2) (number_1 < number_2 ? number_1 : number_2)
#define max(number_1, number_2) (number_1 < number_2 ? number_2 : number_1)

int main() {
    int start_position, end_position;
    int teleportation_start_position, teleportation_end_position;

    cin >> start_position >> end_position >> teleportation_start_position >> teleportation_end_position;
    cout << start_position << " " << end_position << " " << teleportation_start_position << " " << teleportation_end_position << "\n";

    start_position = min(start_position, end_position);
    end_position = max(start_position, end_position);

    teleportation_start_position = min(teleportation_start_position, teleportation_end_position);
    teleportation_end_position = max(teleportation_start_position, teleportation_end_position);

    cout << start_position << " " << end_position << " " << teleportation_start_position << " " << teleportation_end_position << "\n";
}

And I get with the input of

3 10 8 2

I get

3 10 8 2
3 10 2 2

Why is it 2 2?

It still doesn't work when I delete the things I defined (#define). I only inserted a code snippet.

Note #2: I'm new to c++ with mostly pythonic habits.

Note #3: The bad habits are because this is competitive programming.


Solution

  • The error is that you are re-using the teleportation_start_position variable.

    teleportation_start_position = min(teleportation_start_position, teleportation_end_position);
    

    Before this line the state of your program is:

    • teleportation_start_position = 8
    • teleportation_end_position = 2

    But after, it is:

    • teleportation_start_position = 2
    • teleportation_end_position = 2

    So in the next line you are doing:

    teleportation_end_position = max(teleportation_start_position, teleportation_end_position);
    // teleportation_end_position = max(2, 2);