在STL中使用sort()对数组进行排序 [英] using sort() in STL to sort an array

查看:968
本文介绍了在STL中使用sort()对数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个问题的代码:写一个方法来对字符串数组进行排序,以便所有的字谜彼此相邻。
如果我的容器是vector,它将非常简单,因为vector有迭代器并且可以在STL sort函数中使用,这是下面的代码:
但是如果容器是一个数组怎么办? Array没有迭代器,也不能使用sort()直接对数组进行排序。我想知道有没有办法创建一个数组迭代器,以便我可以使用sort()直接对数组进行排序?
谢谢!

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); ???
}


推荐答案

As(如C)数组可以被转换为指向第一个元素的指针(但是,请不要将数组与指针混淆)你可以使用指针来确定开始和结束,所以你写:

As (like in C) array can be casted to pointer to the first element (but please, do not confuse array with pointer) you can use pointers to determine begin and end, so you write:

sort(strarr, strarr + len, compare);

或者如果您使用C ++ 11(或Boost),您可以使用 array class:

or if you use C++11 (or Boost) you can use array class:

template<std::size_t N>
int sortStrarr(std:array<string, N>& strarr, int len){
    sort(strarr.begin(), strarr.end(), compare);
}

这篇关于在STL中使用sort()对数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆