As far as I know stack.push() have a O(1) time complexity but is it actually correct if I use a stack of string.
stack<string> stringStack;
string inputString;
while(cin >> inputString) {
stringStack.push(inputString); // what is the time complexity of this line
}
It's constant, O(1).
The operation involves updating the reference or pointer to the new element, and this process is independent of the size of the string.
I'm pretty sure you're wrong. A copy of
inputString
is added to the stack; creating a copy takes time in $$$O(\text{len(inputString)})$$$.https://cplusplus.com/reference/stack/stack/push/
"The content of this new element is initialized to a copy of val."
I think you're right, a good solution would be a stack of pointers of references to strings, so the time to push them is constant as they're basically an adress
I appreciate your response, I'll make sure to fix my mistake right away :)
There is second overload which moves instead of copying https://en.cppreference.com/w/cpp/container/stack/push