Tom Lilletveit
Tom Lilletveit

Reputation: 2002

C++: Lexicographic comparing strings using operators

As I understand it if I compare two strings using the operators like the lesser-than (<) C++ will compare them Lexicographically. I´d like to take advantage of this searching through a array and return the smallest lexicographic value. And for than I am using a temporary value for finding the smallest one string smallest.

As you see I´ve given it the value z. What is the letter/symbol with the highest lexicographic value? is there any static variable That is already defined I can assign it to in C++?. What is the norm when doing this?

string VectorPQueue::extractMin() {
    string smallest = "z";
    int *count = new int;
    if (elems.size() != 0) {
        for (int i = 0; i < elems.size(); i++)
        {
            if ((elems.get(i)) < smallest) {
                smallest = elems.get(i);
                *count = i;
            }
        }

    } else {
        ErrorException("ERROR: pqueue is empty.");
        return "";
    }

    elems.remove(*count);
    printElements();
    return smallest;
}

Upvotes: 2

Views: 1654

Answers (2)

templatetypedef
templatetypedef

Reputation: 372972

You might want to use the std::min_element algorithm, which will use the normal less-than operator to retrieve an iterator to the smallest element in a range. This completely eliminates the need for you to write this function on your own.

Hope this helps!

Upvotes: 9

Pete Becker
Pete Becker

Reputation: 76418

Just set smallest to the first string, then start searching at the second one.

Upvotes: 4

Related Questions