1
我有一个程序打印出数组中冒泡排序的通行证,并且想要尝试添加显示(通过文本颜色更改)在哪里进行交换的功能每次传递数组。到目前为止,我尝试过的所有内容都会更改所有文本颜色,或者不会更改任何内容(如当前示例所示)。有人有主意吗?更改数组中元素的文本颜色
#include <iostream>
#include <Windows.h>
#include <iomanip>
#include <string>
using namespace std;
void sortArrayAscending(int *array, int size);
void printArray(int *array, int);
void printUnsortedArray(int *array, int size);
int main()
{
HANDLE a = GetStdHandle(STD_OUTPUT_HANDLE);
SetConsoleTextAttribute(a, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
string hyphen;
const string progTitle = "Array Sorting Program";
const int numHyphens = 100;
hyphen.assign(numHyphens, '-');
const int size = 8;
int values[size] = { 21, 16, 23, 18, 17, 22, 20, 19 };
cout << hyphen << endl;
cout << " " << progTitle << endl;
cout << hyphen << endl;
cout << "\n This program will sort two identical arrays of numbers using a Bubble Sort"<< endl;
cout << "\n Array 1 -- Ascending Order: \n" << endl;
printUnsortedArray(values, size);
cout << endl;
sortArrayAscending(values, size);
cin.ignore(cin.rdbuf()->in_avail());
cout << "\n\n\n\nPress only the 'Enter' key to exit program: ";
cin.get();
}
void sortArrayAscending(int *array, int size)
{
const int regTextColor = 2;
const int swapTextColorChange = 4;
HANDLE screen = GetStdHandle(STD_OUTPUT_HANDLE);
int temp;
bool swapTookPlace;
int pass = 0;
do
{
swapTookPlace = false;
for (int count = 0; count < (size - 1); count++)
{
if (array[count] > array[count + 1])
{
swapTookPlace = true;
temp = array[count];
array[count] = array[count + 1];
array[count + 1] = temp;
if (swapTookPlace)
{
SetConsoleTextAttribute(screen, FOREGROUND_GREEN | FOREGROUND_INTENSITY);
if (array[count] > array[count + 1])
{
SetConsoleTextAttribute(screen, swapTextColorChange);
}
if (pass < 9)
{
cout << fixed << setw(2) << " Pass # " << (pass + 1) << " : ";
pass += 1;
printArray(&array[0], size);
}
else if (pass >= 9)
{
cout << fixed << setw(2) << " Pass # " << (pass + 1) << " : ";
pass += 1;
printArray(&array[0], size);
}
}
}
}
} while (swapTookPlace);
}
void printArray(int *array, int size)
{
for (int count = 0; count < size; ++count)
cout << " " << array[count] << " ";
cout << endl;
}
void printUnsortedArray(int *array, int size)
{
cout << " Unsorted ";
for (int count = 0; count < size; ++count)
cout << " " << array[count] << " ";
cout << endl;
此代码取消引用未初始化的指针执行的。相反,你可以只使用'WORD',而不是指针 –
正确,我会编辑 – Edd
谢谢你的帮助!我对C++和编程非常陌生,所以我对你的解决方案有几个疑问:这些代码在程序中的哪个位置?我尝试在其中一个或另一个实施它,无法让程序运行。我的第二个问题是,这种解决方案是否能够仅格式化数组中的交换顺序的元素,例如,如果我有一个数组“{1,3,2,4}”,并且按升序排序,但想要只会对'[3]'和'[2]'着色,因为它们是物品交换的地方。 – McBraunie