2

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;
}
templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
Tom Lilletveit
  • 1,872
  • 3
  • 31
  • 57
  • nb: esp if you have mixed case, it will compare them by subtractive differences/numerical value, which isn't necessarily "lexicographic" to a human (i.e. the set of people who do not write/maintain software for a living). – user7116 Jan 10 '13 at 20:48
  • As an FYI, you want to throw the ErrorException, not just construct it. It looks like you're using the Stanford CS106B libraries here (this seems like it's being done for the Priority Queue assignment), so you can just use the error() function. – templatetypedef Jan 10 '13 at 20:53
  • 3
    ...dynamically allocating the `counter` makes exactly no sense. – Griwes Jan 10 '13 at 20:53
  • 3
    @TomLilletveit Personally, I've never found memory leaks to be terribly fun. – Andrew Durward Jan 10 '13 at 21:04

2 Answers2

9

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!

templatetypedef
  • 362,284
  • 104
  • 897
  • 1,065
4

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

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
  • I did this, it introduced some bugs - so I just thought of doing it this way instead. (like if I remove all the items, and then it start searching at position 1 etc) - Array out of bounds – Tom Lilletveit Jan 10 '13 at 20:52
  • 2
    It didn't **introduce** some bugs; it **exposed** them. Still, `min_element` is probably better overall. – Pete Becker Jan 10 '13 at 21:06