0

Hi what is the solution ?

i have a file like this :
0 1 2 C
10 1 2 S
7 1 2 C
11 1 2 S
9 3 43 C
10 3 43 S
1 3 43 C
101 3 43 S

with this code :

ifstream in("fout2.txt");
    if (in) {
    vector<string> lines;
    string line;
while (getline(in, line))
lines.push_back(line);
sort(lines.begin(), lines.end(), [](const string& a, const string& b) {
// Use the first word for comparison
return a.substr(0, a.find_first_of(' ')) <
b.substr(0, b.find_first_of(' '));
    });
for_each(lines.begin(), lines.end(), [](const string& s) {
std::cout << s << '\n';
    });
}

i obtaint this :

0 1 2 C
1 3 43 C
10 1 2 S
10 3 43 S
11 1 2 S
101 3 43 S
7 1 2 C
9 3 43 C

but i want an output like this :

0 1 2 C
1 3 43 C
7 1 2 C
9 3 43 C
10 1 2 S
10 3 43 S
11 1 2 S
101 3 43 S

thanks

3
Contributors
2
Replies
13
Views
3 Years
Discussion Span
Last Post by Schol-R-LEA
0

You could try an algorithm as follows:

Create a new list that has your sorted list.
input_list -> initially has unsorted lines.

while ( !input_list.empty() ) {
  search smallest element, add this to a new list. // this is a O(n) operation.
  delete this entry from input_list. 
}

HTH.

0

The simplest solution is to convert the first token (that is, the first contiguous series of characters) of each line to an integer, and sort by the integers. Given this approach, it would then make more sense to use an STL map(), which automatically sorts itself according to a predicate passed as an optional template parameter, rather than sorting the list after the fact. Since the default sorting uses the less comparison, you may not even need the predicate.

std::map<int, std::string> sorted_strings = std::map<int, std::string>(); 

while (getline(in, line)) 
{
    std::stringstream ss;
    ss << in;
    int key;
    ss >> key;
    sorted_strings[key] = in;
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.