Home > Back-end >  Function that takes array of strings and returns the longest one
Function that takes array of strings and returns the longest one

Time:08-19

Trying to get this to work, but CodeBlocks gives me this error:

error: no matching function for call to 'max(char[4][10], int)'

Tried getting rid of template <>, made function to receive char*, nothing works.

How do I make this function to receive an array of strings (char[]), and spit out the longest one?

EDIT: Yeah, I missed that thing with index, now corrected. The problem is not gone.

#include <iostream>
#include <cstring>

template<class number>
number max(number numbers[], int n)
{
    number maximum = numbers[0];
    for (int i = 1; i < n; i  )
    {
        if (numbers[i] > maximum)
            maximum = numbers[i];
    }
    return maximum;
}

template<>
char* max (char** strings, int n)
{
    int maxlen = strlen(strings[0]);
    int maxind = 0;

    for (int i = 1; i < n; i  )
    {
        if (strlen(strings[i]) > maxlen)
        {
            maxlen = strlen(strings[i]);
            maxind = i;
        }
    }
    return strings[maxind];
}

int main()
{
    char strings[4][10] = {"Cat", "Dog", "CANNIBALS", "Witch"};
    int test_int[4] = {1, 2, 3, 4};
    double test_dble[5] = {1.2, 3.1, 5223e11, 23, -1000.0};
    std::cout << "int max(): " << max(test_int, 4) << std::endl;
    std::cout << "double max(): " << max(test_dble, 5) << std::endl;
    std::cout << "char** max(): " << max(strings, 4) << std::endl;
    return 0;
}

CodePudding user response:

If we simplify your code a lot we can boil it down to this:

#include <cstring>

char* max(char** strings, int n) { return nullptr; }

int main() {
    char strings [4][10] = {"Cat","Dog","CANNIBALS","Witch"};
    max(strings, 4);
    return 0;
}

As Avi Berger pointed out char[4][10] isn't convertible to char**. The following would compile:

#include <cstring>

char* max(char (&strings)[4][10], int n) { return nullptr; }

int main() {
    char strings [4][10] = {"Cat","Dog","CANNIBALS","Witch"};
    max(strings, 4);
    return 0;
}

Obviously this is only useful for char[4][10], you could make it more generic like this:

#include <cstring>

template <int a, int b>
char* max(char (&strings)[a][b], int n) { return nullptr; }

int main() {
    char strings [4][10] = {"Cat","Dog","CANNIBALS","Witch"};
    max(strings, 4);
    return 0;
}

Now that we have a and b there is no point in passing in n, it might as well reduce to this:

#include <cstring>

template <int a, int b>
char* max(char (&strings)[a][b]) { return nullptr; }

int main() {
    char strings [4][10] = {"Cat","Dog","CANNIBALS","Witch"};
    max(strings);
    return 0;
}
  • Related