Search code examples
c++typesvectorcastingpush-back

Typecasting for vector pushback operation in C++


I have two vectors

std::vector<std::string> outputStack, operatorStack;

At some point, I need to pop some elements out of one stack and push it into another stack.

while(operatorStack.back().compare(L_BRACKET)) {
    outputStack.push_back(operatorStack.pop_back());
}

However, eclipse throws an error, invalid arguments. But works fine when I type cast the input.

outputStack.push_back((std::string)operatorStack.pop_back());

Now, why is this typecasting needed? I was reading (mostly in C++ Primer) that typecasting needs to be avoided according to C++11.


Solution

  • std::vector::pop_back() returns void. You need to get the back() first, then pop it.

    outputStack.push_back(operatorStack.back());
    operatorStack.pop_back();
    

    This is quite common in standard library container pop functions, for exception safety reasons. A value_type returning pop would generally imply a copy construction, which could throw, meaning the container will lose an element that isn't copied succesfully by the caller. So pop() and back() or front() operations are separated.