Stuart Jecoroxy
Stuart Jecoroxy

Reputation: 43

Sort by lexicographical_compare() function

Is there any way to sort a string using the lexicographical_compare() function in C++?

I can do it by STL sort, but my question is about the lexicographical_compare() function.

Upvotes: 0

Views: 21679

Answers (2)

Ben
Ben

Reputation: 9713

The question is poorly worded. Of course, std::lexicographical_compare doesn't modify anything, so to sort you can't just use std::lexicographical_compare: you have to use std::sort (or equivalent) somehow. The correct answer to "how do you lexicographically sort a container of std::strings?" is std::sort(vec.begin(), vec.end()) because operator< on std::strings is a lexicographical comparison.

On the assumption that your question is an example of a broader question of how do you sort range of containers into lexicographic order (which is really more of a question of how do you use custom comparison function objects to alter the behavior of std::sort), you just provide std::sort with a comparison operator. For example:

// A function objecto to do lexicographical comparisons
template <typename Container>
bool LexCompare(const Container& a, const Container& b) {
    return std::lexicographical_compare(a.begin(), a.end(),
                                        b.begin(), b.end());
}

// Use that comparison function to sort a range:
template <typename ContainerIterator>
void sort_by_lexicographical_comapre(ContainerIterator beg,
                                     ContainerIterator end)
{
    std::sort(beg, end, LexCompare<typename ContainerIterator::value_type>);
}


int main() {
    std::vector<std::string> v;
    v.push_back(std::string());
    v[0].push_back('1');
    v[0].push_back('3');
    v[0].push_back('0');
    v.push_back(std::string());
    v[1].push_back('1');
    v[1].push_back('3');
    sort_by_lexicographical_comapre(v.begin(), v.end());

    for (int i = 0; i != v.size(); ++i) {
        std::cout << v[i] << "\n";
    }
    return 0;
}

You can change the above to have v have type std::vector<std::vector<int> > and push back integers into them and it will still work.

Upvotes: 7

juanchopanza
juanchopanza

Reputation: 227468

You don't need std::lexicographical_compare to sort a string. You just need the std::sort algorithm:

#include <iostream>
#include <string>
#include <algorithm>

int main()
{
  std::string s("qwertyuioplkjhgfdsazxcvbnm");
  std::cout << s << "\n";
  std::sort(s.begin(), s.end());
  std::cout << s << "\n";
}

The same applies to sorting a collection of strings:

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>

int main()
{
  std::vector<std::string> v{"apple" , "Apple" ,"AppLe" , "APPLe"};
  for (const auto& s : v)
    std::cout << s << " ";
  std::cout << "\n";
  std::sort(v.begin(), v.end());
  for (const auto& s : v)
    std::cout << s << " ";
  std::cout << "\n";
}

Upvotes: 6

Related Questions