1

I want to call a function reverse(BidirectionalIterator first, BidirectionalIterator last) from <algorithm> header file inside my function, whose name is also reverse(int).

code:

#include<iostream>
#include<algorithm>

using namespace std;

class Solution{
public:
    int reverse(int x){
        string num = to_string(x);
        reverse(num.begin(), num.end());
    }
};

I thought it would automatically call the appropriate function based on the parameters passed just like function overloading. But, it doesn't.

I tried:

namespace algo{
    #include<algorithm>
}

But it is giving a lot of errors.

cigien
  • 57,834
  • 11
  • 73
  • 112
Vold
  • 29
  • 9
  • 3
    Don't use `using namespace std;`. Instead, use `std::reverse` to be explicit. More reading: https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – NathanOliver Oct 26 '20 at 13:12
  • Trying to stick an entire header into an arbitrary namespace won't also put the implementation of that header into the same arbitrary namespace. You'll also need to change the source code of that header file (in this case, the Standard C++ Library source code), and recompile that library. Alternatively, just don't go there. – Eljay Oct 26 '20 at 13:27
  • @Eljay Could you explain why function overloading did not work here? – Vold Oct 26 '20 at 13:37
  • There is no function overloading here. Solution has only one member function: `int reverse(int)`, which expects one `int` parameter. When the compiler tries to match up `reverse(num.begin(), num.end());` to `int reverse(int)` it doesn't match, so the compiler emits an error. – Eljay Oct 26 '20 at 13:41

1 Answers1

5

Ahh, now you're experiencing the reason people on StackOverflow are always yelling about not using using namespace std;. The issue is that you're bringing the whole namespace into the global namespace, which'll lead to clashes like this.

If you delete that line, however, now all of your imported functions stay in the std namespace, so you could do:

#include<iostream>
#include<algorithm>

// BAD
// using namespace std;

class Solution{
public:
    int reverse(int x){
        std::string num = std::to_string(x);
        std::reverse(num.begin(), num.end());
        return std::stoi(num); // Don't forget to return!
    }
};
fas
  • 1,393
  • 10
  • 20
scohe001
  • 15,110
  • 2
  • 31
  • 51