Home > OS >  Sort a c list and remove all duplicate strings
Sort a c list and remove all duplicate strings

Time:10-07

#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <list>
#include <string>

using namespace std;

istream& GetLines(istream& is, list<string>& list) {
    string str;
    if (list.size() > 0) {
        list.clear();
    }
    while (getline(is, str, is.widen('\n'))) {
        list.push_back(str);
    }

    return is;
}

void Print(const list<string>& list) {
    for (auto it = list.cbegin(); it != list.cend(); it  ) {
        cout << *it << endl;
    }
}

void SortAndUnique(list<string>& list) {}

int main() {
    list<string> list;
    ifstream f(
        "/home/jacksparrow/Downloads/university/project/module3/Module_3/"
        "T2-list/src  /main.cpp");

    // Read the file into list
    if (!f.is_open() || !GetLines(f, list).eof()) {
        cout << "Opening error: Error reading main.cpp" << endl;
        return EXIT_FAILURE;
    }

    Print(list);
    cout << "---" << endl;

    // Sort and unique
    SortAndUnique(list);
    Print(list);

    cout << "---" << endl;
    // Print again
    Print(list);

    return 0;
}

I have got the above code in a file "main.cpp" and, I read this file "main.cpp" into a list "list list;", now what I want to do is to sort that list into alphabetical order and remove the duplicate strings. Also, this upper code is my main.cpp file in which I included (#include "list.cpp" ) file which's code is written below and does 3 functions:

  1. Reads the file data into the list "getline()".
  2. Prints the list Print()
  3. sort that "list" into alphabetical order and, removes the duplicate strings SortAndUnique().

CodePudding user response:

The proper way to solve this is as suggested to read the documentation about the container you are using and in std::list Operations, you'll find this list:

Public member function Description
merge merges two sorted lists
splice moves elements from another list
remove
remove_if
removes elements satisfying specific criteria
reverse reverses the order of the elements
unique removes consecutive duplicate elements
sort sorts the elements

The linked member functions are overloaded:

std::list::sort:

  • void sort();
    
  • template< class Compare >
    void sort( Compare comp );
    

std::list::unique:

  • size_type unique();
    
  • template< class BinaryPredicate >
    size_type unique( BinaryPredicate p );
    

In your case you do not need to provide a Compare functor or a BinaryPredicate since the overloads taking no arguments already do what you want.

  • Related