I'm trying to write a program that sorts strings by their lengths and use it on a text file I have to print out the ten shortest and ten longest lines.
I am not sure if I am on the right path and I am stuck. If someone could look over it and tell me where to go from here I would appreciate it! The biggest problem I am having is if I am suppose to read in the text file in the main and call my sort function and print out the lines there?? Is that right?
Are you able to write an algorithm which sorts a vector of integers? If yes, then just replace if(int1 < int2) with if(str1.length() < str2.length()) the rest does not change (except the obvious).
If no, either see bubble sort in wikipedia (there is some pseudocode) or just use std::sort (form algorithm header).
Your sorting algorithm is a bit strange. I see what your idea is, but it's hard to find the error.. Unless it is only that you missed {} around lines 57,58..
No. I only mentioned integers because sorting them is more obvious. My point was that if you can write a sorting algorithm, you need only trivial changes to make it work with a different type and different method of comparison.
Did you try the adding the {}s ? I have a feeling this could be your whole problem..
I see. He only applies binary_search to the 1st i elements of second, which may be sorted at that point.
Other questions: Where are the elements of second initialized? Line 58 only?
Is he relying on a default value of 0 for the elements?
What is the role of second? Is it to hold indexes for ordering the lines by length.
ie: so that lines[ second[i] ] would be in order of increasing length?
I can't follow the logic so I shall duck out!
int main()
{
readLines("bible.txt");
for(int i = 0; i < lines.size(); i++)
cout << lines[i] << '\n';
}
Bible.txt is part of the beginning of the Bible. I am using Microsoft Visual Studio and put Bible.txt under resource files. I don't need to read it in somehow before I compile .cpp file do I?