Error using Max_Element with String Vector

Viewed 35

I'm implementing an algorithm to return a vector string array with only the largest elements in the vector string array of entrance:

vector<string> solution(vector<string> inputArray) {
vector<string> s;
auto m = *max_element(inputArray.begin(),inputArray.end());
 
for(int i=0;i<inputArray.size();i++){
    if(inputArray[i].size() == m.size())
    {
        s.push_back(inputArray[i]);
    }
}


return s;

It works for every test case except in the case the entry string vector is {"enyky", "benyky","yely","varennyky"}. 'm' should return a pointer to "varennyky", but it returns a pointer to "yely" instead.

I digged in to the documentation for max_element, but cant find what I'm doing wrong. Can anybody help me?

1 Answers

Your function is comparing the strings lexicographically, which is the default comparison in case of strings.

To illustrate, consider the following example:

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

// Print a vector of strings
void print_vec(std::vector<std::string> vec)
{
    for (const auto& el : vec) {
        std::cout << el << " ";
    }
    std::cout << std::endl;
}

// Compares strings by length
bool less_length(const std::string& s1, const std::string& s2)
{
    return s1.length() < s2.length();
}

int main()
{
    std::vector<std::string> test_0 = {"enyky", "benyky","yely","varennyky"};

    // Default sort and max element
    std::sort(test_0.begin(), test_0.end());
    print_vec(test_0);

    const auto largest_0 = *std::max_element(test_0.begin(), test_0.end());
    std::cout << "Largest member (lexicographically): " << largest_0 << '\n' << std::endl;

    // Sort and max element by string size
    std::sort(test_0.begin(), test_0.end(), less_length);
    print_vec(test_0);

    const auto largest_1 = *std::max_element(test_0.begin(), test_0.end(), less_length);
    std::cout << "Largest member (by string length): " << largest_1 << std::endl;

}

The first part of the program runs what you are doing in your function: it finds the maximum element based on lexicographic ordering. According to that ordering, the largest string is yely, you can see that by the output from sort.

The second part uses a custom comparison function, borrowed directly from this book. It uses string length to determine the order in the max_element call and the result is what you were looking for. Again, the sorted vector is also printed for clarity.

Related