Search code examples
c++arraysstringparameters

Array of strings as function parameter in C++


I have found online the following way to get the length of an array of strings in C++:

template <size_t array_length> int foo(string (&arr)[array_length])
{
    return array_length;
}

Now consider the following (nonsense) program, which uses the above function.

template <size_t array_length> bool canConstruct(string target, string (&wordBank)[array_length])
{
  int m = foo(wordBank);
  int n = target.size();
  for(int i = 0; i < m; i++)
  { 
      if(m<n){return (wordBank[i]=="a");}
  }
  return false;
}


int main() 
{
    string wordbank[6] = {"r","a","t","ge","t","u"};
    bool output;
    output = canConstruct("targets", wordbank);
    cout << output << endl;
    return 0;
}

This program runs, but I would like to know if there is an equivalent realization of the "canConstruct" function without the use of templates. The "array_length]" argument in this function is never used in this function, so should not be necessary? But somehow this was the only way that I managed to implement these functions.


Solution

  • std::span lets the caller pass contiguous memory without the callee knowing whether it comes from a C array, std::vector, etc. As suggested in the comments, in C++, std::array is preferable to a C array.

    bool canConstruct(string target, std::span<string> wordBank)
    {
        int m = wordBank.size();
        ...
    }
    
    int main()
    {
        std::array<string, 6> wordbank{"r", "a", "t", "ge", "t", "u"};
        bool output = canConstruct("targets", wordbank);
        ...
    }