Changed completely due to suggestions from other member. Most problems solved, still having problems. Now won’t output any names from the array in main. Not sure if I’m passing them back correctly from function.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
void bubblesort(string[], const int);
int sub = 0;
int main()
{
const int maxsize = 100;
string friendArray[maxsize];
ifstream friends;
friends.open("myFriends.dat");
while (sub < maxsize)
{
getline(friends, friendArray[sub]);
sub++;
}
bubblesort(friendArray, maxsize);
cout<<friendArray[0]<<" "<<friendArray[1]<<" "<<friendArray[2];
system("pause");
return 0;
}
void bubblesort(string *array, const int size)
{
bool swap;
string temp;
do
{
swap = false;
for (int count = 1; count < (size - 1); count++)
{
if(array[count-1] >array[count])
{
temp = array[count-1];
array[count-1] = array[count];
array[count] = temp;
swap = true;
}
}
}
while(swap);
}
Your problem isn’t necessarily that
tempinsidebubblesortis not achar, the problem is thatarrayis declared as astringand not astring[].The reason you’re getting the error is because
array[count+1]is of typechar, andtempis of typestring.std::swapexpects two elements of the same type.However, that may be the least of your problems, your code doesn’t compile for quite a few reasons. Not just that but you’re passing in
maxsizetobubblesortat each iteration. There’s a flaw in both your logic and your syntax.EDIT: Since you’re still having trouble getting the sorting to work, here’s a working modification of your code:
bubblesortcould also be written as:void bubblesort(std::string *array, size_t size). There’s no difference in this case since, when passed to a function, arrays decay into pointers.Since arrays are passed by reference, a pointer to the first element, any modifications made to
arrayinside ofbubblesortwill actually be modifying your array inmain. So that’s how arrays are “returned”.std::vectoris a good alternative to the standard array, since it automatically resizes and obviously contains the length of the internal array so that you don’t have to pass the size everywhere you pass anstd::vector. You can also use it the same way as a regular array.