c++ - Sorting words in a character array -


for given array, need write function sort words alphabetically:

char strings [][10] = {     "hello",     "world",     "computers",     "are",     "awesome" }; 

i've tried write function sortwords using insertion sort, think swap function isn't working:

void swap(char *e1, char *e2) {     int tmp = *e1;     *e1 = *e2;     *e2 = tmp; }  void sortwords( char (* words2darray)[10], unsigned short length ) {     unsigned int i, curpos;     char curchars[10];      for(i = 1; < length; i++) {         // copy current word curchars         strncpy_s(curchars, words2darray[i], 10);         curpos = i;          // compare , move word correct position         while(curpos > 0 && strcmp(curchars, words2darray[i-1]) > 0) {             swap(words2darray[curpos], words2darray[curpos-1]);             curpos--;         }     } } 

i've attempted debugging code using local windows debugger , found curchars being copied properly.

can please explain me doing wrong , how should go solving problem? i'm not allowed use std::string in problem. no full solutions please!

you can use std::sort:

std::sort(std::begin(strings), std::end(strings), cmp); 

this requires comparator. whipped 1 based on strcmp.

see live on ideone

#include <algorithm> #include <iostream> #include <cstring>  int main() {     char const* strings[] = {         "hello",         "world",         "computers",         "are",         "awesome"     };      struct {          bool operator()(char const* a, char const* b) const {             return (a && b)? 0 > strcmp(a,b) : < b;         }     } cmp;      std::sort(std::begin(strings), std::end(strings), cmp);      (auto& s : strings)         std::cout << s << "\n"; } 

note took liberty of making array elements char* instead of char[]. reasons pointed out carl norum.


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -