Sorting strings

Write your question here.
Write a method to sort an array of strings so that all the anagrams are next to each other.

My problem is why we should use &s1[0] instead of &s; similarly, why we should use &s1[0]+s1.length() instead of &s1+s1.length()??

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
#include <algorithm>
using namespace std;

bool cmp(string s1, string s2){
    sort(&s1[0], &s1[0]+s1.length());
    sort(&s2[0], &s2[0]+s2.length());
    return s1 < s2;
}

int main(){
    string s[] = {
        "axyz", "abc", "yzax", "bac", "zyxa", "fg", "gf"
    };
    sort(s, s+7, cmp);
    for(int i=0; i<7; ++i)
        cout<<s[i]<<endl;
    return 0;
}


if I print the content as follows
1
2
3
4
5
string s1 = "Hello!!";
cout<<"1  "<<&s1<<"\n";
cout<<"2  "<<&s1[0]<<"\n";
cout<<"3  "<<&s1+s1.size()<<"\n";
cout<<"4  "<<&s1[0]+s1.size()<<"\n";


It would be like this

1  003FF96C
2  Hello!!
3  003FFA4C
4
The & operator takes the address of the thing that follows it.

Given string s1:

&s1[0] --> take the address of s1[0], which is the first character in the string. Hence, the address is of the first character in the string.

&s1 --> take the address of s, which is a std::string object. Hence, the address is of an object that manages a character string.

Given some_type s[] = { ...:

&s[0] --> take the address of s[0], which is the first element in the array (in your case it is a std::string, but it could be an integer or a double or a struct or anything).

s --> this is the same* as &s[0].

&s --> take the address of s, which is itself the address of the first element in the array. Hence, it is the address of an address.

Hope this helps.

* caveats apply.

Thanks a lot. It is clear and understandable.
Topic archived. No new replies allowed.