output of sort() function

This one should be easy, Using the standard string class if the input is baadcc Is there to a way to change the output of the sort() function to look like
character: a Count: 2
character: b Count: 1
character: c Count: 2
character: d Count: 1...

do I need a different version of the sort function
or maybe a function to display the string in the desired manner after it is sorted?

here is my program so far...




1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#include <algorithm>
#include <cctype>
#include <functional>
#include <string> 
#include <iostream>

using namespace std;

string makelower(const string& t);
inline unsigned CountWords( const string& s );
string removepunc(const string& t, const string& punc); 

int main()
{  
    int number_used =0;
    string TEXT, punc = (",:;.?!'/ "); 
    cout << "Enter text to test" << endl;
    getline (cin, TEXT); 
    cout << "Word Count:" << CountWords(TEXT);
    TEXT = makelower(TEXT);
    TEXT = removepunc(TEXT, punc);
    sort(TEXT.begin(), TEXT.end());
    cout << endl << TEXT << endl;
system("pause");
return 0;
}

string makelower(const string& t)
{
       string temp(t);
       for (int i=0; i < t.length(); i++)
            temp[i] = tolower(t[i]);
       return temp;
}
inline unsigned CountWords( const std::string& s )
  {
  string x = s;
  replace_if( x.begin(), x.end(), ptr_fun <int, int> ( isspace ), ' ' );
  x.erase( 0, x.find_first_not_of( " " ) );
  if (x.empty()) return 0;
  return std::count( x.begin(), unique( x.begin(), x.end() ), ' ' ) + !isspace( *s.rbegin() );
  }
string removepunc(const string& t, const string& punc)
{
       string nopunc;
       int t_length = t.length();
       int punc_length = punc.length();
       for (int i=0; i < t_length; i++)
       {
          string achar = t.substr(i,1);
          int location = punc.find(achar, 0);
          if (location < 0 || location >= punc_length)
          nopunc = nopunc + achar;
       }
       return nopunc;
}


Last edited on
Use std::unique_copy(). Then iterate over the the new string counting the occurrences of each character in the sorted original string with std::count();

http://www.cplusplus.com/reference/algorithm/unique_copy/
http://www.cplusplus.com/reference/algorithm/count/
Topic archived. No new replies allowed.