在 STL 中使用 sort() 对数组进行排序
我正在为一个问题编写代码:编写一个方法来对字符串数组进行排序,以便所有字谜彼此相邻.如果我的容器是vector,那就很简单了,因为vector有迭代器,可以在STL排序函数中使用,代码如下:但是如果容器是一个数组呢?数组没有迭代器,不能使用 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); ???
}
推荐答案
由于(就像在 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
类:
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);
}
相关文章