-1

I am trying to find the smallest element in a array of strings but I can't figure out how to do this. I came up with this code idea which works perfectly for integers but does not work for strings. This will compile, although it only checks the first character in string for its ASCII value. In other words, in an array of strings: lists[5] = { "aaa", "z", "cccc", "tt", "jjj"}; lists[1] or "z" is the smallest element of the strings. However, because 'a' is a lower ASCII value the code will print out Smallest aaa instead of Smallest z. Now I know I could do some kind of deep compassion of each character in the string using .length but I want to use something that is simple that can solve this because I want to add it to a function that will be overloaded to a integer so I can go back and forth between string and integer comparisons. But if this is not possible I will just have two separate functions to handle each.

What if any suggestions do you have on how to find the smallest element in a array of strings?

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

using namespace std;

int main() {


string  lists[5] = { "aaa", "z", "cccc", "tt", "jjj"};
    string smallests;
    smallests = lists[0];
    for (int i = 0; i < 5; i++){
        cout << smallests << endl;
        if (lists[i] < smallests){   // Flip < to > to find largest
            smallests = lists[i];
        }
    }
    cout << "Smallest " << smallests << endl;
    cout << *min_element(lists, lists + 5) << endl;

return 0;
}
omni
  • 580
  • 1
  • 6
  • 16
T.Malo
  • 512
  • 1
  • 7
  • 24
  • 4
    Smallest as in length? Or by alphabetical order? – Cory Kramer Oct 03 '14 at 19:56
  • Well, length but I can now see that alphabetical order would come in play. As in string lists[5] = { "a", "z", "c", "t", "j"}; would all be the same length. But one thing at a time because that check would be the code I have now haha. – T.Malo Oct 03 '14 at 20:00

2 Answers2

6

The simplest thing to do is to note that std::min_element can be passed a custom comparison function. So, let's define what it means to be smallest.

From the comments, it appears that you want shorter strings, and then to sort them lexicographically.

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

bool smallest(std::string const & lhs, std::string const & rhs) {
    if (lhs.size() < rhs.size())
        return true;
    if (lhs.size() == rhs.size() && lhs < rhs)
        return true;
    return false;
}

int main() {
    std::string lists[5] = { "aaa", "z", "cccc", "tt", "jjj"};
    std::cout << *std::min_element(lists, lists + 5, smallest) << "\n";
}

Which outputs:

z
Bill Lynch
  • 80,138
  • 16
  • 128
  • 173
-3

The < operator wont work on strings in C. You need to use strcmp provided by string.h

http://www.tutorialspoint.com/c_standard_library/string_h.htm

Your code to compare then becomes:

if (strcmp(lists[i], smallests) < 0) {
    smallests = lists[i];
}
user2479438
  • 414
  • 4
  • 4