2015-09-14 3 views
2

У меня есть некоторая рабочая сортировка, состоящая из чисел в порядке возрастания, денежные значения от 500 до 25000. Однако мне нужны адреса, назначенные каждому из этих значений, но эти адреса (Пример: 151 Желудь) Не следуйте алфавитному или цифровому рисунку, например, от наивысшего до самого низкого.Как сортировать массивы строк в определенном шаблоне

Есть ли какой-либо алгоритм сортировки, который мог бы помочь мне здесь? Мой текущий код будет опубликован ниже, но моя цель состоит в том, чтобы у заданных массивов были соответствующие адреса и значения, начиная с [0] - [6].

#include<iostream> 
#include<string> 
#include <iomanip> 
#include <cstdlib> 


using namespace std; 

int totalsList(int value[7], string address[7]); 

void lookUp(int value[], string address[]); 
void display(int value[], string address[]); 
void showHighest(int value[], string address[]); 
void sortArray(int[], int); 
void sortStrings(string[], string); 
void showArray(const int[], int); 

int main() { 
    //Definitions 
    int size = 0; 
    int value[7] = { 500, 1000, 1500, 6000, 15000, 20000, 25000 }; 
    string address[7]{ "151 Acorn", "120 Xenia", "161 Acorn", "161 Acorn", "200 Main", "200 Acorn", "500 Arcade" }; 

    // MAIN MENU 
    int choice; 
    cout << "County Auditor's Tax Look Up Program:\n"; 
    cout << "1.) Display The Data.\n"; 
    cout << "2.) Look up Taxes.\n"; 
    cout << "3.) Sort taxes in ascending order.\n"; 
    cout << "4.) Show Property with largest tax due.\n"; 
    cout << "5.) Exit Program.\n"; 
    cin >> choice; 

    while (choice <= 5) { 

     if (choice == 1) { 
      display(value,address); 
     } 

     if (choice == 2) { 

      lookUp(value,address); 

     } 

     if (choice == 3) { 

      sortArray(value, 7); 
      sortString(address, 7); 
      cout << "Sorted Values: \n"; 
      showArray(value, 7); 


      system("pause"); 



} 


     if (choice == 4) { 
      showHighest(value, address); 
     } 
    } 

    //exit 
    if (choice == 5) { 
     return 0; 
    } 
    system("pause"); 



} 


void lookUp(int value[], string address[]) { 
    string add; 
    cout << "Enter Address: "; 


    getline(cin, add); 
    getline(cin, add); 
    // Validate String entry 
    if (add != address[0] || add != address[1] || add != address[2] || add != address[3] || add != address[4] 
     || add != address[5] || add != address[6] || add != address[7]) { 
     cout << "This address is not found, please re-enter\n"; 

    } 

    // Look up function shows cost and address according to arrays 
    int valCor = 0; 
    if (add == address[0]) { 
     valCor = 500; 
     cout << "The address: " << add << " has tax due of: " << "$" << valCor << endl; 
    } 
    if (add == address[1]) { 
     valCor = 1000; 
     cout << "The address: " << add << " has tax due of: " << "$" << valCor << endl; 
    } 
    if (add == address[2]) { 
     valCor = value[2]; 
     cout << "The address: " << add << " has tax due of: " << "$" << valCor << endl; 
    } 
    if (add == address[3]) { 
     valCor = value[3]; 
     cout << "The address: " << add << " has tax due of: " << "$" << valCor << endl; 
    } 
    if (add == address[4]) { 
     valCor = value[4]; 
     cout << "The address: " << add << " has tax due of: " << "$" << valCor << endl; 
    } 
    if (add == address[5]) { 
     valCor = value[5]; 
     cout << "The address: " << add << " has tax due of: " << "$" << valCor << endl; 
    } 
    if (add == address[6]) { 
     valCor = value[6]; 
     cout << "The address: " << add << " has tax due of: " << "$" << valCor << endl; 
    } 

    system("pause>nul"); 

} 

void display(int value[], string address[]) { 
    // Display all arrays in table format 
    cout << "All Addresses and Owed Taxes, correspondingly: \n"; 
    cout << "----------------------------------------------\n"; 

    cout << address[0] << " Tax: $" << value[0] << endl; 
    cout << address[2] << " Tax: $" << value[0] << endl; 
    cout << address[3] << " Tax: $" << value[0] << endl; 
    cout << address[4] << " Tax: $" << value[0] << endl; 
    cout << address[5] << " Tax: $" << value[0] << endl; 
    cout << address[6] << " Tax: $" << value[0] << endl; 
    system("pause"); 

} 

void showHighest(int value[], string address[]){ 

    cout << "Highest Value: \n"; 
    cout << "The Highest Property tax is on the location " << address[6] << "with a tax of: $" << value[6]; 


} 

void sortArray(int array[], int size) 
{ 
    bool swap; 
    int temp; 

    do 
    { 
     swap = false; 
     for (int count = 0; count < (size - 1); count++) 
     { 
      if (array[count] > array[count + 1]) 
      { 
       temp = array[count]; 
       array[count] = array[count + 1]; 
       array[count + 1] = temp; 
       swap = true; 
      } 
     } 
    } while (swap); 
} 

void sortString(string array[], int size) 
{ 
    bool swap; 
    int temp; 

    do 
    { 
     swap = false; 
     for (int count = 0; count < (size - 1); count++) 
     { 
      if (array[count] > array[count + 1]) 
      { 
       temp = array[count]; 
       array[count] = array[count + 1]; 
       array[count + 1] = temp; 
       swap = true; 
      } 
     } 
    } while (swap); 
} 

void showArray(const int array[],int size) 
{ 
    for (int count = 0; count < size; count++) 
     cout << "$" << array[count] << "\n"; 
    cout << endl; 
} 
+0

Вместо параллельных массивов подумайте об одном массиве 'struct'. Вы можете использовать 'std :: sort' для сортировки. –

+0

Я предлагаю вам создать структуру из двух членов: 'int' для вашего денежного значения и' string' для адреса. Имейте один массив структур вместо двух отдельных массивов. Затем, когда вы сортируете массив по значению, адреса появятся. – Logicrat

+0

Не могли бы вы дать мне небольшой пример или ссылку? Звучит полезно, я никогда не видел этот метод. – Ace

ответ

1

Я бы использовал std::sort. Вам понадобится ваша собственная структура данных для пакетной сборки int и std :: string.

Сторона Примечание: Старайтесь избегать using namespace std;. Это bad practice

+0

Каждый инструмент имеет свое место. Никакой инструмент по своей сути плохой практике. 'using namespace std;' не является хорошей идеей в глобальном пространстве имен в заголовочном файле (потому что это будет иметь тенденцию добавлять работу), но это хорошая идея в короткой небольшой исследовательской программе или специальном инструменте (потому что там экономит работу), а некоторые другие случаи не ясны. Короче говоря, абсолютизм «плохой практики» - это просто дерьмо. Вы могли бы также сказать, что указатели - плохая практика. Они могут испортить вещи. Программирование на C++ требует разведки. Нельзя делать это хорошо, применяя механические абсолютные правила. –

+0

Я делаю много исследований по методу сортировки и структуры, но не могу найти для этого очень конкретной идеи. Есть ли способ, которым вы можете предоставить базовый вариант? – Ace

Смежные вопросы