1. ## sort a vector

hi I nees create a vector and reserve it dimension
Code:
vector <string> lines (DIMENSION);
lines[0] = "mi";
lines[1] = "gi";
sort(lines.begins(), lines.end());
Problem: the sort put the strings at the end of vector because it match they with "" (blank). I'd like put it at begin...How do?
thanks

2. Originally Posted by mickey0
Problem: the sort put the strings at the end of vector because it match they with "" (blank). I'd like put it at begin...How do?
thanks
sort the new strings only
Code:
sort(lines.begins(), lines.begin()+2);
Kurt

3. You mean, you've created a vector of strings with several elements filled with data strings (like "mi" and "gi"), and several strings are still empty. So when you go to sort it, you get something like "", "", "", "gi", "mi"? And you want "gi", "mi", without the empty strings?

The simplest way that comes to mind is to remove the empty strings first, and then sort it. Or you could remove them afterwards, I suppose. Or you could just process the vector starting at the first non-blank element after it was sorted.
Code:
#include <iostream>
#include <vector>
#include <string>

int main() {
std::vector<std::string> data(5);
std::vector<std::string>::iterator i;

data[0] = "one";
data[1] = "two";
std::sort(data.begin(), data.end());

for(i = data.begin(); i != data.end() && *i == ""; i ++);

for( ; i != data.end(); i ++) {
std::cout << '"' << *i << '"' << std::endl;
}

std::cin.get();
return 0;
}
Output:
Code:
"one"
"two"
Or, even more simply (and this works for sorted and non-sorted vectors):
Code:
#include <iostream>
#include <vector>
#include <string>

int main() {
std::vector<std::string> data(5);
std::vector<std::string>::iterator i;

data[0] = "one";
data[1] = "two";
std::sort(data.begin(), data.end());

for(i = data.begin(); i != data.end(); i ++) {
if(*i != "") std::cout << '"' << *i << '"' << std::endl;
}

std::cin.get();
return 0;
}
The output is the same as above.

 Or, even easier, see ZuK's reply above. [/edit]

4. If you dont actually need the unfilled slots of the vector right away, then perhaps it would be better to write:
Code:
vector <string> lines;
lines.reserve(DIMENSION);
lines.push_back("mi");
lines.push_back("gi");
sort(lines.begin(), lines.end());
Otherwise, you have to keep track of the number of elements currently in use yourself.

5. You could also write your own comparator. It should return false if the left string is empty, then true if the right string is empty, then use the regular string less than function.

That means that empty strings would always be last and the rest of the strings would be sorted normally. This is especially useful if you are providing a valid string at non-sequential indexes (although I'm not sure when you'd need to do that).