EverNoob 2021-03-03 21:59 采纳率: 75%
浏览 74
已采纳

C++ a^=b b^=a a^=b bug 求解

练手写了简答选择排序代码如下:

#include <iostream>
#include <array>

using namespace std;

#define DEBUG 1

template <typename T>
void swap_pos(T &a, T &b){ 
	#if DEBUG 
	cout << a << " " << b << endl; 
	#endif

	a ^= b; 

	#if DEBUG 
	cout << a << " " << b << endl; 
	#endif

	b ^= a;	

	#if DEBUG 
	cout << a << " " << b << endl; 
	#endif

	a ^= b;	

	#if DEBUG 
	cout << a << " " << b << endl; 
	#endif
}

template <typename T>
void printArr(T const& arr){
	for(auto it = arr.begin(); it != arr.end(); it++){
		cout << *it << " ";
	}
}

template <typename T>
void selectSort(T& arr){
	int nSize = arr.size();
	//add one elem as min_holder
	int min_pos = 0;
	for(int i=0; i<nSize; i++){
		min_pos = i;
		for(int j=i+1; j<nSize; j++){
			if(arr[min_pos] > arr[j]){
				min_pos = j;
			}
		}
		swap_pos(arr[i],arr[min_pos]); //bug at i=3, min_pos=3 for some reason
		#if DEBUG
		printArr(arr); cout << "\n";
		#endif
	}
}

int main(){
	array<int, 10> og_arr = {2,3,4,1,5,6,9,8,7,0};
	array<int, 10> arr(og_arr);

	selectSort(arr);
	printArr(arr);
}

swap_pos 会在 i,min_pos 均为3的循环出错,打出信息如下:

compiler:gcc version 8.1.0 (x86_64-posix-seh-rev0, Built by MinGW-W64 project)

还请高人指点这是哪方面的问题,多谢!

  • 写回答

2条回答 默认 最新

  • 爱晚乏客游 2021-03-04 14:23
    关注

    看不懂你为什么要用预处理?你的问题就是在52行处交换的时候,要是i==min_pos的话,你执行完14行之后,arr[i]=0,arr[min_pos]=0,这就是i=min_pos的结果,所以应该在交换的前面添加一句,当i!=min_posd的时候才能交换,否则不交换。

    		if(i!=min_pos){
    		    swap_pos(arr[i], arr[min_pos]); //bug at i=3, min_pos=3 for some reason
            }
    		printArr(arr); cout << "\n";
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?