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
Pointers can act as iterators, so you just need pointers to the beginning and just past the end of the array.
int sortStrarr(string strarr[], int len){
sort(&strarr[0],&strarr[len],compare) ;
//sort(strarr's iterator.begin, strarr's iterator.end, compare); ???
}
We have to use sort function to sort the string array.
int main()
{
string arr[5] = {"e", "b", "c", "d", "a'};
sort(arr, arr+5);
for(int i=0; i<5; i++)
{
cout<<arr.at(i)<<" ";
}
return 0;
}
The free functions std::begin() and std::end() (since C++11) are specialized for array types, but the size must be known to the compiler:
template <typename T, std::size_t N>
int sortStrarr(T array[N])
{
// 'using' allows ADL to select best overload
using std::begin;
using std::end;
std::sort(begin(array), end(array));
}
If you have only the start and (run-time) size, then you can use pointers as the iterators:
template <typename T>
int sortStrarr(T array[], size_t len)
{
std::sort(array, array+len);
}
You can use sort() for an array. Pointers act as iterators.
Example:
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
string arr[5]={"BBB","AAA","CCC","FFF", "EEE"};
sort(arr,arr+5);
for(string i: arr)
{
cout << i << endl;
}
}
and the output is:
AAA
BBB
CCC
EEE
FFF
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);
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);
}