Hi! I am generally new to C++. I'm trying to create a phone book kind of program, and sort the input by phone number ascending. My problem is that after I get my numbers sorted, the names do not stay with their respective numbers. How would I sort the names so they stay with their numbers? Currently they are sorting numbers in order, and names alphabetically.
Here is the sorting portion of my code, everything before this is just output and populating the arrays name and number.
Here is my full program so far;
I want the input to be along the lines of
Bob Steve Joe Carl
22 57 1 20
After sort:
Joe Carl Bob Steve
1 20 22 57
But I'm getting
Bob Carl Joe Steve
1 20 22 57
I haven't learned about vectors yet. Or structs. Fairly new to C++ and my book doesn't even have anything about vectors in it. Is there a way that I can keep the names with the numbers in parallel arrays and not a vector or pair?
#include <iostream>
#include <string>
int main() // *** int main
{
constint size = 4;
std::string name[size]; // declaring an array name
int number[size] = {0}; // initialise to all zeroes
std::cout << "Please input 10 names and their corresponding numbers\n" ;
for( int i = 0; i < size; ++i )
{
std::cout << "name #" << i+1 << "? " ;
std::cin >> name[i] ; // assumes that the name has no embeeded spaces
std::cout << "number? " ;
std::cin >> number[i] ; // we assume that the user enters a valid number
} // end for
// print the unsorted names and numbers
std::cout << "\nbefore sort\n----------\n" ;
for( int i = 0; i < size; ++i )
std::cout << name[i] << ": " << number[i] << '\n' ;
// sort on names: keep associated numbers in sync with the names
// we assume that we haven't encountered functions as yet
for( int i = 0; i < size; ++i )
{
for( int j = i+1; j < size; ++j )
{
if( name[j] < name[i] ) // if name[i] should appear before name [j]
{
// swap the names (could use std::swap for this)
const std::string temp_str = name[i] ;
name[i] = name[j] ;
name[j] = temp_str ;
// swap the corresponding numbers (could use std::swap for this too)
constint temp_num = number[i] ;
number[i] = number[j] ;
number[j] = temp_num ;
} // end if
} // end inner for
} // end outer for
// print the sorted names and numbers
std::cout << "\nsorted on name\n----------\n" ;
for( int i = 0; i < size; ++i )
std::cout << name[i] << ": " << number[i] << '\n' ;
} //end main
@JLBorges OMG Many many thanks! That works perfectly. (and yes, I am just now learning of functions, but wanted to get more familiar with sorting before I tried splitting it all up. That is why my code only consisted of main)