Home > other >  Vector Resizing in C works only when adding cout statement?
Vector Resizing in C works only when adding cout statement?

Time:11-18

vector<string> solution(vector<string> inputArray) {
    int n = inputArray.size();
    vector<string> outputString(n);
    int maxSize, curPos = 0;
    for(auto &i: inputArray)
    {
        int currentSize = i.size();
        if(currentSize > maxSize)
        {
            maxSize = currentSize;
            curPos = 0;
            outputString[curPos  ] = i;
        }else if (currentSize == maxSize)
        {
            outputString[curPos  ] = i;
        }
    }
    cout<<curPos;
    outputString.resize(curPos);
    return outputString;
}

In the original code without the cout line, the outputString resulted in an empty vector. But upon adding the cout line, the problem gets magically solved. What could be the reason behind this?

CodePudding user response:

maxSize is uninitialised so your code has undefined behaviour. UB produces surprising results like printing something changes the behaviour of the program.

By using reserve and then adding strings to the vector your code can be a lot simpler:

vector<string> solution(const vector<string>& inputArray) {
    size_t n = inputArray.size();
    vector<string> outputString;
    outputString.reserve(n)
    for(auto &i: inputArray)
    {
        int currentSize = i.size();
        if(outputString.empty() || currentSize > outputString.front().size())
        {
            outputString.clear();
            outputString.push_back(i);
        }else if (currentSize == outputString.front().size())
        {
            outputString.push_back(i);
        }
    }
    return outputString;
}

CodePudding user response:

int maxSize;

You declare maxSize, but not initialize it, so maxSize is uninitialized. And you use maxSize to compare with currentSize , which makes it undefined behavior. Undefined behavior can do anything, so that's your problem.

Change to:

int maxSize = std::numeric_limits<int>::min(); // in <limits> header
  • Related