Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using sort() in STL to sort an array

I am writing code for a question which is: Write a method to sort an array of strings so that all the anagrams are next to each other. If my container is vector, it will be very simple, since vector has iterator and can be used in STL sort function which is the code below: But what if the container is an array? Array has no iterator and cannot use sort() to sort the array directly. I would like to know is there any way to create a array iterator so that I can use sort() to sort the array directly? Thank you !

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

bool compare(string s1, string s2){
  sort(s1.begin(), s1.end());  //sort return void, not the sorted result!!!!!!!!!!
  sort(s2.begin(), s2.end());
  return s1<=s2;
}


void sort_string(vector<string> &v){
    sort(v.begin(), v.end(), compare);
}
#
If I want to use array itertor:

bool compare(string s1, string s2){
        sort(s1.begin(), s1.end());
        sort(s2.begin(), s2.end());
        return s1<=s2;
}


int sortStrarr(string strarr[], int len){

    //sort(strarr's iterator.begin, strarr's iterator.end, compare); ???
}
like image 310
bunny Avatar asked Dec 05 '22 11:12

bunny


1 Answers

Pointers can act as iterators, so you just need pointers to the beginning and just past the end of the array.

like image 157
Jerry Coffin Avatar answered Dec 18 '22 15:12

Jerry Coffin