How to alphabetically sort strings?

こ雲淡風輕ζ 提交于 2019-11-29 05:23:35

You could use std::set or std::multiset (if you will allow repeated items) of strings, and it will keep the items sorted automatically (you could even change the sorting criteria if you want).

#include <iostream>
#include <set>
#include <algorithm>

void print(const std::string& item)
{
    std::cout << item << std::endl;
}

int main()
{
    std::set<std::string> sortedItems;

    for(int i = 1; i <= 5; ++i)
    {
        std::string name;
        std::cout << i << ". ";
        std::cin >> name;

        sortedItems.insert(name);
    }

    std::for_each(sortedItems.begin(), sortedItems.end(), &print);
    return 0;
}

input:

  1. Gerardo
  2. Carlos
  3. Kamilo
  4. Angel
  5. Bosco

output:

Angel
Bosco
Carlos
Gerardo
Kamilo
user7968404

You can use the sort function:

vector<string> s;
sort(s.begin(),s.end());

Your code implements a single-pass of bubble sort. Essentially missing the 'repeat until no changes are made to the array' loop around the outside.

The code does not take care when the names are already in order. Add the following

else if(int(names[y][z])<int(names[y+1][z]))
            break;  

To the if statement.

You are using too much unnecessary loops. Try this simple and efficient one. You need to just swap when a string is alphabetically latter than other string.

Input
5
Ashadullah
Shawon
Shakib
Aaaakash
Ideone

Output
Aaaakash
Ashadullah
Ideone
Shakib
Shawon


#include <bits/stdc++.h>
using namespace std;
int main()
{
    string s[200],x[200],ct,dt;
    int i,j,n;
    cin>>n;
    for(i=0;i<n;i++)
    {
        cin>>s[i];
    }

    for(i=0;i<n;i++)
    {
        for(j=i+1;j<n;j++)
        {

            if(s[i]>s[j])
            {

                ct=s[i];
                s[i]=s[j];
                s[j]=ct;

            }

        }

    }
    cout<<"Sorted Name in Dictionary Order"<<endl;
    for(i=0;i<n;i++)
    {
        cout<<s[i]<<endl;
    }
    return 0;


}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!