4

Is this not allowed? Can someone please explain why?

Algorithms.h

namespace Algorithms
{
  int kthLargest(std::vector<int> const& nums, int k);    
}

Algorithms.cpp

#include "Algorithms.h"
namespace
{
int kthLargest(std::vector<int> const& nums, int start, int end, int k)
{
   <implementation>
}
} // end anonymous namespace

namespace Algorithms
{
   int kthLargest(std::vector<int> const& nums, int k)
   {
      return kthLargest(nums, 0, nums.size() - 1, k);
   }
} // end Algorithms namespace

The error I run into is:

> /usr/bin/c++   -I../lib/algorithms/inc  -MD -MT
> lib/algorithms/CMakeFiles/algorithms.dir/src/Algorithms.o -MF
> lib/algorithms/CMakeFiles/algorithms.dir/src/Algorithms.o.d -o
> lib/algorithms/CMakeFiles/algorithms.dir/src/Algorithms.o -c
> ../lib/algorithms/src/Algorithms.cpp
> ../lib/algorithms/src/Algorithms.cpp: In function ‘int
> Algorithms::kthLargest(const std::vector<int>&, int)’:
> ../lib/algorithms/src/Algorithms.cpp:70:50: error: too many arguments
> to function ‘int Algorithms::kthLargest(const std::vector<int>&, int)’
> return kthLargest(nums, 0, nums.size() - 1, k);
elixenide
  • 44,308
  • 16
  • 74
  • 100
betelgeuse
  • 79
  • 5
  • Note that std has [`std::nth_element`](https://en.cppreference.com/w/cpp/algorithm/nth_element). – Jarod42 Dec 31 '18 at 09:41

1 Answers1

6

Your code leads to recursion call. When kthLargest is called inside Algorithms::kthLargest, the name kthLargest will be found at the namespace Algorithms, then name lookup stops, no further scopes (e.g. global namespace) will be examined. After that, overload resolution is performed and fails because arguments don't match.

You can change it to

namespace Algorithms
{
   int kthLargest(std::vector<int> const& nums, int k)
   {
      // refer to the name in global namespace
      return ::kthLargest(nums, 0, nums.size() - 1, k);
      //     ^^
   }
}

or

namespace Algorithms
{
   using ::kthLargest;  // introduce names in global namespace
   int kthLargest(std::vector<int> const& nums, int k)
   {
      return kthLargest(nums, 0, nums.size() - 1, k);
   }
} 
songyuanyao
  • 169,198
  • 16
  • 310
  • 405