[SOLVED] c++ sorting problem

Started by
24 comments, last by phil67rpg 11 years, 6 months ago
The C++ standard library has (among other things) a very powerful toolbox of template tools that compliment each other.
The template tools are divided into three areas: Containers, Algorithms, and Iterators.

Containers hold your data, Iterators access your data, and Algorithms operate on your date.
(Algorithms use Iterators to access the data held in the Containers)

This is what Brother Bob is talking about when he said:

Make a structure that contains all the information you need.

struct person {
int number;
int pancakes;
};

Sort an array of persons based on the pancakes-field.


The container you want to use, is probably std::vector. std::vector is a array that can be resized easily, and is the default "go to" container you mostly want to use, unless you are trying to do something specific, and until you know the pros and cons of the other containers. (Each container, including std::vector, has tradeoffs - these tradeoffs are important to learn, but when in doubt, std::vector is usually a safe bet).

The iterator being used in this case is happening behind the scenes, so you don't need to worry about it. But if you're curious, it's a random-access iterator. (You'll learn more about these in the future, so don't worry if you don't understand it right now - I didn't bothered looking at them for years, and the fine details of how iterators work internally can be mostly ignored until later. Containers are more important, and Algorithms also. Understanding iterators helps you understand how Algorithms and Containers work, but aren't required knowledge to use them).

The algorithm you want to use in this case is std::sort. std::sort takes a range of elements* in a container, and sorts them in order from least to greatest. Ofcourse, what's "least" or "greatest" depends on the type of data given... data is expected to be able to provide their own comparison functions, or else a comparison function has to be passed to std::sort. Ints have built-in comparison functions (< > != ==, etc...).

*An 'element' is a fancy name that means "a piece of data a container holds". Like an array, myVector[0] accesses the first element in the container.

So, using std::vector to hold our pancake-eating heroes, and using std::sort to sort them by the number of pancakes eaten, we get this code:
struct Person
{
int id; //The number used to identify the person.
int pancakes; //The number of pancakes eaten.
};
bool PersonPancakeCompare(const Person &personA, const Person &personB)
{
//If personA is less than personB, return true.
//Here, we're measureing by number of pancakes eaten.
return (personA.pancakes < personB.pancakes);
}

int main()
{
std::cout << "How many people are eating pancakes?\n"
<< "Num people: ";

int numPeople = 0;
std::cin >> numPeople;

//A std::vector container of the 'Person' struct.
//The vector is currently empty (we haven't added anyone yet).
std::vector<Person> people;

for(int i = 0; i < numPeople; i++)
{
Person person;
person.id = i; //Keep track of what number this person is.

std::cout << "How many pancakes did person " << (i+1) << " eat?\n"
<< "Pancake count: ";

std::cin >> person.pancakes;

//Add the person to the end of the std::vector.
//push = "add to", back = "the back of the vector".
//push_back(person) = "add to the back of the vector, the data in 'person'".
people.push_back(person);
}

//Use std::sort algorithm on the std::vector, from the vector's begin()ing, to the vector's end().
//Since the struct "Person" is a new type of struct, we need to tell std::sort what makes a 'Person' less-than or greater-than
//another Person. So we provide our own comparison function, "PersonPancakeCompare()" to tell std::sort() how to compare 'Person' variables.
std::sort(people.begin(), people.end(), PersonPancakeCompare);

//Now, we can print out the results.
std::cout << "\n\n-------------------------\n"
<< "Results:" << std::endl;

//Loop over the entire (already-sorted) vector, and print out each person.
for(int i = 0; i < people.size(); i++)
{
Person &person = people;
std::cout << "Person " << (person.id + 1) << " ate " << person.pancakes << " pancake(s)!" << std::endl;
}

return 0;
}


std::sort() isn't a bubble sort, though, because in this situation a bubble sort isn't needed. If however, this is a homework question, and the teacher specified "use a bubble sort", then this code doesn't qualify and would fail the teacher's requirement. But ofcourse this isn't a homework question, is it? Because if it is, you conveniently forgot to mention it in your original post. wink.png
Advertisement
wow that is alot to learn,I have decided to rewrite my program using classes and member funcitions,and the heap,it is some good practice for me,I am also using pointers.I like to oop techniques when I can but I have tenous understanding of pointers, but I am doing some studying up on them.here is the code I am using.

#include <iostream>
using namespace std;
int *pancakes = new int[10];
int *pancakes_one = new int[10];
int *pancakes_two = new int[10];
class Person
{
public:
void sort_pancakes(int*);
void num_pancakes(int*);
void output_pancakes(int*);
private:
int number;
int pancakes;
int panckes_one;
int pancakes_two;
};
void Person::num_pancakes(int *pancakes)
{
for(int i=0; i < 10; i++)
{
cout << "Enter number of pancakes eaten: ";
cin >> pancakes;
}
}
void Person::sort_pancakes(int *pancakes_one)
{
for(int i=0; i<10;i++)
{
for(int j=0;j<i;j++)
{
if(pancakes_one<pancakes_one[j])
{
int temp = pancakes_one;
pancakes_one = pancakes_one[j];
pancakes_one[j] = temp;
}
}
}
}
void output_pancakes(int *pancakes_two)
{
for(int k=0; k<10;k++)
{
cout << "Person " << k << " ate " << pancakes_two[k] << " pancakes." << endl;
}
}
int main()
{
Person pancake;
pancake.num_pancakes(pancakes);
pancake.sort_pancakes(pancakes_one);
pancake.output_pancakes(pancakes_two);
int test;
cin >> test;

return 0;
}


I am however getting a linker error:
LINK : C:\Users\phil\Desktop\size\Debug\size.exe not found or not built by the last incremental link; performing full link
1>size.obj : error LNK2019: unresolved external symbol "public: void __thiscall Person::output_pancakes(int *)" (?output_pancakes@Person@@QAEXPAH@Z) referenced in function _main
1>C:\Users\phil\Desktop\size\Debug\size.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I have traced the problem to the "pancake.output_pancakes(pancakes_two);"
line of code.
something is wrong in my member function, I think??
Yep, you made your member function forgett to be a member-function, and declared it just as a regular function. smile.png
void output_pancakes(int *pancakes_two)

Should be:
voidPerson::output_pancakes(int *pancakes_two)

For your:
int *pancakes = new int[10];
int *pancakes_one = new int[10];
int *pancakes_two = new int[10];


It really is much better if you use vectors:
std::vector<int> pancakes(10, 0); //Ten ints initialized to 0.

But even if you don't use vectors, you shouldn't use dynamic (heap) memory here. Stack is better, whenever you can:
int pancakes[10] = {0};

One of the reasons is if you use heap memory, it's easy to forget to release it when finished... like in your code. You new'd it, but forgot to call delete. Every new must also have a delete, but it's better code to avoid calling new and delete directly, and let objects manage their own lifetimes by putting them on the stack. (RAII)

In modern C++, even using dynamic/heap memory should be done through manager classes 99% of the time. (std::smart_ptr, std::weak_ptr, std::unique_ptr, etc... if you are using the latest standard - which if you aren't now, you soon will be - so it's good to get that into your mind ahead of time).

To summarize these tips for success in C++:

  • Whenever possible, prefer stack over heap. They are safer, and declares intent better.
  • Whenever possible, prefer references over pointers. They are safer, and declares intent better.
  • Whenever possible, prefer smart pointers over raw pointers for dynamic memory. They are safer, and declare intent better.
  • Whenever possible, prefer pancakes over waffles. They are tastier, and leave syrup in your beard for later snacking.
I have decided to finish my sorting problem,I have made some changes to my code,I am using two arrays to store pancakes and people,I then sort the values inputted,by using a bubble sort,I then output the values.the hard part is getting the values to parallel each other. In other words I only want the pancakes to be sorted but I want the persons to be related to each pancake value.Here is my code:

#include <iostream>
using namespace std;
int pancake[11];
int person[11];
int main()
{
for(int i=1;i<=10;i++)
{
cout << "Enter number of pancakes eaten: ";
cin >> pancake;
person=i;
}
for(int i=1; i<=10; i++)
{
for(int j=1;j<=i;j++)
{
if(pancake>pancake[j])
{
int temp = pancake;
pancake=pancake[j];
pancake[j]=temp;
}
}
}
for(int i=1; i<=10; i++)
{
for(int j=1;j<=i;j++)
{
if(person>person[j])
{
int temp = person;
person=person[j];
person[j]=temp;
}
}
}
for(int i=1; i<=10;i++)
{
cout << "Person " << person << " ate " << pancake << " pancakes." << endl;
}
int test;
cin >> test;
return 0;
}


I really want to finish this project.
If you have two arrays you can't sort them independently. That will give a sorted pancake array and a sorted person array without preserving the relation between them. If you want to sort both of them by the number of pancakes then sort the pancakes, but every time you swap two elements of the pancake array swap the corresponding members of the person array.
This is a question I have asked people in interviews. There are basically three solutions:

  1. Create an array of structs that contain both the person and the pancakes (Brother Bob's solution).
  2. Sort the array of pancakes, but swap elements in the array of persons in parallel (SiCrane's solution).
  3. Create an array of indices initialized to {0,1,2,3,...} and sort it by comparing the entries in the array of pancakes.

Solution 3 is a good choice if there are multiple arrays that you need to sort in parallel or if swapping the entries is expensive.
wow thanks for all the help
I am going to try sicranes solution.
I have decided to rework my code,but now it won't sort my array and output it.

#include <iostream>
#include <stdlib.h>
using namespace std;
int arr[10]={0};
void bubbleSort(int arr[], int n) {
bool swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < n - j; i++) {
if (arr > arr[i + 1]) {
tmp = arr;
arr = arr[i + 1];
arr[i + 1] = tmp;
swapped = true;
}
}
}
}
int main()
{
for(int i=0;i<10;i++)
{
cout << "Enter number of panckes eaten: ";
cin >> arr;
}
int n=10;

for(int j=0;j<10;j++)
{
void bubbleSort(int arr[],int n);
}

for(int i=0; i<10;i++)
{
cout << "Person " << i << " ate " << arr << " pancakes." << endl;
}

system("pause");
return 0;
}


i did this to better understand functions
To call a function, you have to pass in parameters.

"void bubbleSort(int arr[],int n);" is used to create a function. You never actually use the function.

Your "bubbleSort()" function won't know what array to use, and won't know what 'n' is set to, until you actually pass it parameters like this:
bubbleSort(myArray, 10);

Further, you don't need to call the function 10 times (just once in your specific example), so it doesn't need to be in the for() loop.

[hr]

When a function defines parameters, those parameters are variables. When you pass in variables to a function call, you are saying "Set the function's parameters are to the value of the variables I'm passing in to it".

The parameters do not need to have the same name as the variables being passed in. (You are passing in the data your variables hold, not the variables themselves).

Likewise, when a function returns a value, it's returning the data that you can then assign to a different variable.

Example: (this is important to understand)
int myFunction(int parameterA, int parameterB)
{
return (parameterA + parameterB);
}

int main()
{
int result1 = myFunction(15, 20); //Passing in data from temporary variables without names that are set to 15 and 20.
std::cout << "result1: " << result1 << std::endl;

int var1 = 1004;
int var2 = 230;

int result2 = myFunction(var1, var2); //Passing in data held in variables. (The variables aren't passed in, just *copies* of the data they hold)
std::cout << "result2: " << result2 << std::endl;

int result3 = myFunction(var2, 23000); //Passing in data from temporary and non-temporary variables.
std::cout << "result3: " << result3 << std::endl;

system("pause");
return 0;
}


A number like "45" just floating in your code can be thought as (but isn't exactly) an unnamed temporary variable with the value of 45. These are called 'literals'.

When you go:
int myVar = 45;
You are saying, "*copy* the data '45' into the variable 'myVar'".

When you go:
int myOtherVar = myVar;
You are saying: "*copy* the data held in myVar into the variable 'myOtherVar'".

If you have the code:
void myFunction(int param1, int param2);

int main()
{
int myVar = 45; //Holds data equal to the value of '45'.
int myOtherVar = myVar; //Also holds data equal to the value of '45'.

myFunction(myVar, myOtherVar);

return 0;
}


On the line that goes:
myFunction(myVar, myOtherVar);
You are saying "*copy* that data of 'myVar' into myFunction's variable 'param1'. Also, *copy* that data held in 'myOtherVar' into the variable 'param2'."

It is exactly the same as going like this:
int param1 = myVar;
int param2 = myOtherVar;

Except that 'param1' and 'param2' can only be used inside myFunction().

You are *copying* the data, not the variables themselves. (Variables hold data. It's the data you are passing around, not the containers holding them).

This topic is closed to new replies.

Advertisement