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;
}