简体   繁体   中英

Vector Resizing in C++ works only when adding cout statement?

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?

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

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM