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?
#include <iostream>
#include <vector>
#include <string>
usingnamespace 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!
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.