[Solved] Why is this function returning an empty vector? [closed]


There are several issues in your code:

  1. highestSize and add are not initialized. In C++ variables are not default initialized to 0 as you might have expected.
  2. newArray is default constructed to have 0 elements. In this case you cannot use operator[] the way you did. operator[] can access only elements that were allocated. You can use push_back to add to the vector. If your code was changed so that you knew in advance how many entries you will need in newArray, you could also resize the vector and then use operator[] to access the elements. There are some more options like resereving capacity and using push_back, you can see more info here.
  3. It’s better to pass inputArray by const& to avoid an unneeded copy.

A fixed version:

#include <string>
#include <vector>

std::vector<std::string> solution(std::vector<std::string> const & inputArray) {
    int highestSize{ 0 };
    std::vector<std::string> newArray{};
    for (int i = 0; i < inputArray.size(); ++i)
    {
        highestSize = std::max(int(inputArray[i].length()), highestSize);
    }
    for (int i = 0; i < inputArray.size(); ++i)
    {
        if (inputArray[i].length() == highestSize)
        {
            newArray.push_back(inputArray[i]);
        }
    }
    return newArray;
}

A side note: it’s better to avoid using namespace std – see here Why is “using namespace std;” considered bad practice?.

solved Why is this function returning an empty vector? [closed]