Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Rookie question: string sorting with vectors

Status
Not open for further replies.

unbound

Programmer
Sep 8, 2002
1
US
I have a bunch of string stored in a vector, and
sort(i_lines.begin, i_lines.end) won't do it.
I wish to know How can I sort string stored in a vector alphabetically. Thanks.
The full file:


// help !!!!!!

#include <string>
#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
using namespace std;

bool stringsort ( const string &string1, const string &string2)
{
if (string1>string2)
{
return true;
}
else
{
return false;
}
}


string replace_part (const string &src, const string &tgt)
{
// replace part of the source with target
// and output the result.
string result;
result = tgt;

unsigned s_length, t_length;
s_length= src.size ();
t_length= tgt.size ();

if (t_length < s_length )
{
return &quot;Unable to insert.&quot;;
}

unsigned insertat;
insertat = (t_length-s_length) /2;

unsigned looper;
for (looper =0 ; looper < s_length; looper ++)
{
unsigned i_pos;
i_pos = insertat+looper;
result [i_pos] = src[looper];
}

return result;
}



//////////////////////////////////////////////////////////////////////
void main (){

// updated input module
vector <string> i_lines;
string dummy;
unsigned longest =0 ;
cout << &quot;Enter a sequence of first names &quot;<<endl;
cout << &quot;Enter 'endl' to end.&quot; <<endl;
while (cin>>dummy && dummy != &quot;endl&quot;)
{
dummy[0] = toupper(dummy [0]);
i_lines.push_back (dummy);
if (dummy.size() > longest)
{
longest = dummy.size ();
}
}
unsigned nol = i_lines.size () +2 ; // number of lines
sort (i_lines.begin ,i_lines.end );



unsigned t_length = longest + 6;

string temp_star (t_length, '*');
string temp_line (t_length, ' ');
temp_line [0] = '*';
temp_line [t_length -1] = '*';

vector <string> o_lines (nol);
o_lines [0] = temp_star;
o_lines [--nol] = temp_star;

unsigned restoflines;
for (restoflines = 1; restoflines < (nol ); restoflines ++)
{
o_lines [restoflines] = replace_part ( i_lines[restoflines-1],temp_line);
}


unsigned o_looper;

for( o_looper =0 ; o_looper <nol+2; o_looper ++)
{
cout<< o_lines[o_looper]<<endl;
}

}
 
Well, sort() can take a third argument, and something like this:
Code:
    struct string_less : public binary_function<string, string, bool> {
    bool operator()(const string& x, const string& y) const{
    return (strcmp(x.c_str(), y.c_str()) <= 0 ? true : false);
    };
ought to work, if I read the docs correctly.
 


This should work :

sort(i_lines.begin(), i_lines.end());

/JOlesen
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top