with sort algorithm??

could you tell me how to change this with sort algorithm??
1
2
3
4
5
6
7
8
9

void insertName(vector<string>& x, string n){ 
   if( n > x[x.size()-1] ) x.push_back(n);
   else { 
     int i =0;
     while( n > x[i] )i++;   
     x.insert(x.begin()+i,n);
   }
}


here is my whole code:
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
#include <iostream>
#include <vector>
#include <string>
#include <fstream>
using namespace std;
void fillVector(vector<string>& );
void printVector(vector<string> );
void insertName(vector<string>& , string );
int main(){ 
   vector<string> N;
   fillVector(N);
   printVector(N);
   cout<<"Enter name to insert : ";
   string name;
   cin>>name;
   insertName(N, name);
   printVector(N);
   return 0; 
}
void printVector(vector<string> x){
   for(int i=0; i<x.size(); i++)
       cout<<x[i]<<' ';
   cout<<endl;     
}
void fillVector(vector<string>& x){
   string name;
   ifstream fin("names.txt");
   while( fin>>name )		
     x.push_back(name);    
}
void insertName(vector<string>& x, string n){ 
   if( n > x[x.size()-1] ) x.push_back(n);
   else { 
     int i =0;
     while( n > x[i] )i++;   
     x.insert(x.begin()+i,n);
   }
}

Last edited on
I think your first problem is if the vector is empty to avoid a seg-fault:
1
2
3
4
5
6
7
8
void insertName(vector<string>& x, string n){ 
   if( n > x[x.size()-1] ) x.push_back(n); // what if x is empty?
   else { 
     int i =0;
     while( n > x[i] )i++;   // should this be while(n < x[i]) ??
     x.insert(x.begin()+i,n);
   }
}

Also instead of x[x.size()-1] you can use x.back().
no, i know that x isn't empty, i put values from file names.txt, witch is not empty and names in this file are ordered by alphabet. i want to put one another name from keyboard so the order not to abolish, and to do this with sort algorithm and not so, as it's shown above.
Last edited on
what do you need the sort algorithm for??as much as i can see you don't sort your vector, you just add a string.
and instead
1
2
3
 int i =0;
     while( n > x[i] )i++;   // should this be while(n < x[i]) ??
     x.insert(x.begin()+i,n);

you can use
1
2
3
4
5
x.insert(find_if(x.begin(),x.end(),bind2nd(cmp,n)),n);
...
bool cmp(const string& s1,const string& s2){
return s2>s1;
}
lena123 wrote:
no, i know that x isn't empty,

When writing functions you can't make those kind of assumptions. It may be true in your current example, but it won't necessarily be true when you come to use your function in the future, or if someone else uses your function.
Last edited on
Topic archived. No new replies allowed.