There are several issues in your code:
highestSizeandaddare not initialized. In C++ variables are not default initialized to0as you might have expected.newArrayis default constructed to have 0 elements. In this case you cannot useoperator[]the way you did.operator[]can access only elements that were allocated. You can usepush_backto add to the vector. If your code was changed so that you knew in advance how many entries you will need innewArray, you could alsoresizethevectorand then useoperator[]to access the elements. There are some more options like resereving capacity and using push_back, you can see more info here.- It’s better to pass
inputArraybyconst&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]