Sortowanie słów c++

0

Cześć, mam do napisania program, który jako wejście dostaje liczbe n, potem n słów (max lenght 10) i sortuje je leksykograficznie. Coś mi nie działa ;/ to mój kod

#include <iostream>
#include <string.h>
using namespace std;



int main (){
   int n;
   cin >> n;
   char slowo[n][11];
   for(int i = 0; i < n; ++i)
       cin >> slowo[i];

   for(int i = 0; i < n - 1; ++i)
       for(int j = 0; j < n - 1; ++j)
           if(strcmp(slowo[i], slowo[j]) > 0)
               swap(slowo[i], slowo[i + 1]);

   cout << endl;

   for(int i = 0; i < n; ++i)
       cout << slowo[i] << endl;



   return 0;
}
0

Dobra, mam nvm

#include <iostream>
#include <string.h>
#include <algorithm>
using namespace std;

bool cmp(string a, string b){
    if(a < b)
        return 1;
    return 0;
}

int main (){
    int n;
    cin >> n;
    string slowo[n];
    string temp;
    for(int i = 0; i < n; ++i)
        cin >> slowo[i];

    sort(slowo, slowo + n, cmp);
                cout << endl;

    for(int i = 0; i < n; ++i)
        cout << slowo[i] << endl;



    return 0;
}
1
Kondzio33 napisał(a):
bool cmp(string a, string b){
    if(a < b)
        return 1;
    return 0;
}
bool cmp1(const string &a,const string &b) { return a<b; } // wersja 1
bool cmp2(const string &a,const string &b) { static less<const string&> cmp; return cmp(a,b); } // wersja 2 w sumie nie potrzebna
Kondzio33 napisał(a):
    sort(slowo, slowo + n, cmp);

zadziała każdy z wariantów:

sort(slowo,slowo+n,cmp1);
sort(slowo,slowo+n,cmp2);
sort(slowo,slowo+n,less<string>());
sort(slowo,slowo+n);
Kondzio33 napisał(a):
    string slowo[n];

czemu nie:

vector<string> slowo;

?

#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
using namespace std;

int main ()
{
    int n;
    cin>>n;
    vector<string> words(n);
    for(string &word:words) cin>>word;
    sort(begin(words),end(words));
    cout<<endl;
    for(const string &word:words) cout<<word<<endl;
    return 0;
}
2

Zdecyduj się na jeden język: C albo C++.
Nieuzasadniona mieszanka zawsze kończy się pokracznie.

1 użytkowników online, w tym zalogowanych: 0, gości: 1