I am trying to organize the names to print out the order of their respective numbers from largest to smallest. For example, Jae (5), Chris (6), Amy (2), Happy (3), Joy (100). I would want the program to print out, Joy, Chris, Jae, Happy, and Amy. However, the computer prints out something really weird with the names. The program changes the names of the strings. For example, instead of printing out Jae, it may print out Jee, or Ame. Any suggestions to fix this problem?
Just use a bubble sort but make sure to sort the name alongside the number. I'm curious as to why you haven't used a structure to hold the data rather than two separate arrays.
// next_element holds size of data held so
// ive used that for the bubble sort.
int temp;
string temp2;
for (int i = 0; i < next_element; i++)
for (int j = 0; j < next_element - i - 1; j++)
if (p_talk[j] > p_talk[j + 1])
{
// int
temp = p_talk[j];
p_talk[j] = p_talk[j + 1];
p_talk[j + 1] = temp;
// also sort the name
temp2 = p_name[j];
p_name[j] = p_name[j + 1];
p_name[j + 1] = temp2;
}
for (int i = 0; i < next_element ; i++)
{
cout << p_talk[i] << endl;
cout << p_name[i] << endl << endl;
}
Michael
9
Paul
3
John
2
Sam
1
Kim
0
1
Sam
2
John
3
Paul
9
Michael
Thank you so much for your answer. I was thinking about using a structure. However, I didn't know how I would use it in this case. Would you please show me? That would be awesome. Also, any thoughts on why my strings were going crazy?
Sorry, I later realised you asked about structure example. A structure and a vector would be ideal for this scenario... but this really depends on if this code is part of a assignment or you are just learning yourself, i.e. you couldnt use vectors yet if you havent covered them in your lessons :)
#include <iostream>
#include <string>
#include <vector>
struct Data
{
int id;
std::string name;
};
int main()
{
// http://www.cplusplus.com/reference/vector/vector/
std::vector<Data> Names;
int id = 0;
int element = 0;
std::string name;
while (true)
{
std::cin >> id;
if (id == 0)
break;
std::cin >> name;
// create element
Names.push_back(Data());
// populate it
Names[element].id = id;
Names[element].name = name;
element++;
}
// if you want to sort, check out
// http://www.cplusplus.com/reference/algorithm/sort/return 0;
}
But if you want to stick with you previous method using a structure, just allocate in the same way.. only thing that changes really is the way you access the data and assign the values.
I don't understand why you are saying sorry. My goodness, you've helped me out so much. I don't deserve that from you. Hahaha. Anyhow, I'll come back to this one I learned about vectors. Thank you so much!