There are several issues in your code:
highestSize
andadd
are not initialized. In C++ variables are not default initialized to0
as you might have expected.newArray
is 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_back
to add to the vector. If your code was changed so that you knew in advance how many entries you will need innewArray
, you could alsoresize
thevector
and 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
inputArray
byconst&
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]