I have a queue where I happen to push a string on it as my first entry and then I want to dequeue each char of that string individually, I tried two approaches:
string s ="()()h)"
queue<string> q;
q.push(s);
while(!q.empty())
{
string temp = q.front();
q.pop();
}
That results on popping the string as a whole, I have also tried converting the string to an array of char, like this:
string input ="()()h)"
char s[input.size() + 1];
strcpy(s,input.c_str());
Help would be appreciated, thank you.
It seems you want to create a queue of characters. In this case the queue definition can look like it is shown in the demonstrative program below.
#include <iostream>
#include <string>
#include <queue>
int main()
{
std::string s = "()()h)";
std::queue<char> q( std::queue<char>::container_type( s.begin(), s.end() ) );
while ( not q.empty() )
{
char c = q.front();
q.pop();
std::cout << c;
}
std::cout << '\n';
return 0;
}
The program output is
()()h)
To push a string in an already existent queue you can use for example the standard algorithm std::for_each
(or the range-based for loop).
#include <iostream>
#include <string>
#include <queue>
#include <iterator>
#include <algorithm>
int main()
{
std::string s = "()()h)";
std::queue<char> q;
std::for_each( std::begin( s ), std::end( s ),
[&q]( const auto &item )
{
q.emplace( item );
} );
while ( not q.empty() )
{
char c = q.front();
q.pop();
std::cout << c;
}
std::cout << '\n';
return 0;
}