overloaded function with no contextual type information | cannot resolve overloaded function 'swap' based on conversion to type 'int'

假装没事ソ 提交于 2019-12-04 11:36:11

I see that you are using

using namespace std;

So when you type

array[i] = swap;

The compiler cannot disambiguate whether you are referring to the std::swap function or your int swap variable. In fact it looks like it assumed you were referring to the function and tried to somehow convert it to type int. Try renaming your variable to something else.

In general, try to stay away from using directives, to avoid name collisions like this.

array[i] = swap;

This line is causing problem. It is better to change the name of swap local variable, as there exists already a function with same name, in std namespace which is brought into scope by the line using namespace std; which is to be avoided, anyway.

I would also suggest you to declare the variable, inside the if-block where it is actually used:

if(array[i] > array[i + 1])
{
     //declare temp here where it is actually used!
     int temp = array[i + 1]; 
     array[i + 1] = array[i];
     array[i] = temp;
}

Best practice: reduce the scope local variables by delaying their declarations, which means declare them where they are actually used. Do not declare them in the beginning of the function.

Another way to fix the problem in your code is to give the compiler a context which you can by doing this (though I wouldn't suggest this solution; it is just for you to know):

array[i] = (int)swap; //giving compiler contextual type information

When you cast swap to int, the compiler can know that swap refers to the local variable, not the function which is defined in std namespace.

cout << "Sorted: " << bubbleSort(array, arraySize);

The return type of the function is void. There is nothing to print for. If you need to print the sorted array, you need to iterate over the array elements after the function call.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!