BubbleSort-String Comparison

Mar 25, 2017 at 12:36am
Hi. I am a beginner in C++. I was trying to make a function in a program that would read strings from a vector and would sort them by length. I thought that the comparison in strings would compare the lenghts of different strings, but it does not do that. My doubt is: What does the comparison of strings do? Does it compare the first char of the strings? Does it compare lengths? Or neither?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
#include <vector>
#include <string>

using namespace std;


void bubblesort(vector<string> &v)
{
	int i = 1; 
	int iteration = v.size(); //iteration will decrease by one because after one iteration of the bubblesort the last one should already be sorted
	
	while(iteration != 1)
	{
		for (i; i < iteration; i++)
		{
		    string nome_atual = v.at(i); //current name
		    string nome_anterior = v.at(i - 1);//name before

			if (nome_atual < nome_anterior)  // comparison
			{
                            //switching the names if out of order
				v.at(i) = nome_anterior; 
				v.at(i - 1) = nome_atual;
			}
		}

		iteration--; //decreasing the iteration
		i = 1; //reset the counter that will go through the vector
	}


Right now this is sorting by alphabethical order. I want to sort by length. Any help would be great! :)
Thank you for your time!
Last edited on Mar 25, 2017 at 12:42am
Mar 25, 2017 at 12:58am
the built in string comparison is sorting by alphabet, like how a dictionary is ordered from aardvark to zoo

you should sort off

stringvar.length() < otherstring.length()

Mar 25, 2017 at 8:40am
So then, when comparing strings, it compares from character to character until it finds different characters or one of the strings end? Is that it?
Mar 25, 2017 at 10:07am
There is an easier way to sort your strings:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
int main()
{
  vector<string> names = {"Anna", "Elisabeth", "Molly", "Debbie"};
  //#include <algorithm>
  sort(names.begin(), names.end(), [](const string& s1, const string& s2)
  {
    return s1.length() < s2.length();
  });

  for (const string& s: names)
  {
    cout << s << "\n";
  }
  return 0;
}
Mar 25, 2017 at 1:34pm
yes, it compares them character by character using the ascii table's numeric values to sort. A is not the same as a, either, and I think b > Z due to the capitalization. If they are all first letter caps, rest not, or all lower, or all upper, or any other matching pattern like that, it will work as a dictionary. If not, you may not like the results and may want to force them all upper or all lower first.



Topic archived. No new replies allowed.