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