Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
140 views
in Technique[技术] by (71.8m points)

c++ - 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); ???
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

Just Browsing Browsing

2.1m questions

2.1m answers

60 comments

57.0k users

...