-1

The following C++ code when compiled gives the error:

#include <bits/stdc++.h>
using namespace std;

#define IOS ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
#define endl "\n"    

const int N = 5005;

int n, k;
int a[N], prev[N];
int cache[N][N];

int dp(int idx, int take)
{
    if(take < 0)
        return -1e9;
    if(idx == 0)
        return 0;
    int &ans = cache[idx][take];
    if(ans != -1)
        return ans;
    ans = dp(idx - 1, take);
    ans = max(ans, idx - prev[idx] + dp(prev[idx], take - 1));
    return ans;
}   

int32_t main()
{
    IOS;
    memset(cache, -1, sizeof(cache));
    cin>>n>>k;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    sort(a+1, a+n+1);
    int l = 1;
    for(int r=1;r<=n;r++)
    {
        while(a[r] - a[l] > 5)
            l++;
        prev[r] = l - 1;
    }
    int ans = dp(n, k);
    cout<<ans;
    return 0;
}
//AshishGup

Invocation failed [COMPILATION_ERROR] Can't compile file: program.cpp:
In function 'int dp(int, int)': program.cpp:23:23: error: reference to 'prev' is ambiguous
ans = max(ans, idx - prev[idx] + dp(prev[idx], take - 1));

but as soon as the name of the array is changed from prev to prv it works fine. What is happening?

John Kugelman
  • 349,597
  • 67
  • 533
  • 578
BreadCrumb
  • 91
  • 5
  • 3
    What's happening is an example of why ["`using namespace std;`" is bad practice](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice). You will do yourself a big favor if you completely forget that "using namespace std;" exists in C++, and always write correct C++ code. It only takes a short period of time before it becomes completely natural to always explicitly specify classes, templates, and functions in the `std` namespace, and, as an extra bonus, these kinds of mysterious compilation errors will go away, never to be seen again. – Sam Varshavchik Mar 07 '19 at 19:40
  • Most compilers give you more information than this in the error message. In particular, they tell you where the ambiguous names were declared. Error messages can be pretty dense, but wading through them can often give you enough information to see what's really going on. – Pete Becker Mar 07 '19 at 19:51

2 Answers2

4
using namespace std;

It's a bad idea to do that, and this is exactly why. There is ambiguity between your variable prev and the standard library function std::prev.

Also, you should not #include internal compiler headers such as bits/stdc++.h.

Angew is no longer proud of SO
  • 167,307
  • 17
  • 350
  • 455
1

Avoid importing std namespace into global namespace. In your case, you imported std namespace and you defined a global variable named prev which now will conflict with std::prev defined in iterator. https://en.cppreference.com/w/cpp/iterator/prev

Sunil
  • 335
  • 4
  • 11