0
#include <bits/stdc++.h>
using namespace std;
const int N = 1e5 + 10;

vector<int> parent(N);
vector<int> rank(N); // size
void make(int v)
{
   parent[v] = v;
   rank[v] = 1;//"rank" is ambiguous
}
int find(int v)
{
    if (v == parent[v])
    return v;

    return parent[v] = find(parent[v]);
}
void Union(int a, int b)
{
    a = find(a);
    b = find(b);
    if (a != b)
    {
        if (rank[a] < rank[b]) //"rank" is ambiguous
            swap(a, b);
        parent[b] = a;
        rank[a] += rank[b];//"rank" is ambiguous
    }
}

So I was doing Disjoint Union Set (DSU) Data structures in C++. My vector<int> parent is not showing any error but vector<int> rank is showing error of being ambiguous. Why am i getting error:

source>: In function 'void make(int)':
<source>:10:4: error: reference to 'rank' is ambiguous
   10 |    rank[v] = 1;//"rank" is ambiguous
      |    ^~~~
In file included from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/bits/move.h:57,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/bits/stl_pair.h:59,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/bits/stl_algobase.h:64,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/bits/specfun.h:45,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/cmath:1927,
                 from /opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/x86_64-linux-gnu/bits/stdc++.h:41,
                 from <source>:1:
/opt/compiler-explorer/gcc-11.2.0/include/c++/11.2.0/type_traits:1319:12: note: candidates are: 'template<class> struct std::rank'
 1319 |     struct rank
      |            ^~~~
<source>:6:13: note:                 'std::vector<int> rank'
    6 | vector<int> rank(N); // size
      |             ^~~~

Why am I getting this error?.

How do I Fix it ?

Alan Birtles
  • 32,622
  • 4
  • 31
  • 60
  • 2
    https://en.cppreference.com/w/cpp/types/rank https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice – Mat Jan 21 '22 at 08:15
  • Removing `using namespace std;` could solve the problem – akm Jan 21 '22 at 08:23
  • The compiler can't tell if `rank` means `::rank` or `std::rank` you have to use the namespace explicitly. This is caused by the double bad practice of `#include ` which pulls in the whole of the standard library and `using namespace std;` which adds the whole standard library to the global namespace. There are lots of names in `std` which will conflict with commonly used names in your code – Alan Birtles Jan 21 '22 at 08:24
  • Note that you are using global variables. This increases the probability to get such problems. Local variables are generally better protected versus such ambiguity. – Damien Jan 21 '22 at 08:29

0 Answers0