Reputation: 63
I am working a problem to reverse the order of words in a string. For example, if you have str1 = "the sky is blue" then the solution should be "blue is sky the".
Here is my code:
class Solution
{
public:
list<string> words;
void createList(string s)
{
istringstream iss(s);
string token;
while(getline(iss, token, ' '))
{
words.push_back(token);
}
}
string reverseWords(string s)
{
list<string>::iterator iter = words.begin();
string newString = "";
createList(s);
newString.append(*iter);
for (iter = (iter+1); iter != words.end(); iter++)
{
newString.append(" ");
newString.append(*iter);
}
return newString;
}
};
My question is.... Am I using the list iterator correctly? I got a compiler error that said "Line 25: no match for ‘operator+’ " referring to the for loop in reverseWords().
Upvotes: 0
Views: 146
Reputation: 21619
list
does not support random access iterators, therefore using operator+ with list
is not allowed, you would use operator++. You have to access the list elements sequentially, just like you'd have to if you were using your own linked list implementation.
You could use a reverse iterator, to reverse your string.
#include <list>
#include <string>
#include <iostream>
#include <sstream>
using namespace std;
class Solution
{
public:
list<string> words;
void createList(string& s)
{
istringstream iss(s);
string token;
while(getline(iss, token, ' '))
{
words.push_back(token);
}
}
string reverseWords(string& s)
{
list<string>::reverse_iterator iter = words.rbegin();
string newString = "";
createList(s);
for ( ; iter != words.rend(); ++iter)
{
newString.append(" ");
newString.append(*iter);
}
return newString;
}
};
int main(int, char**)
{
string in("The sky is always blue");
Solution s;
string out = s.reverseWords(in);
std::cout << in << std::endl;
std::cout << out << std::endl;
}
Upvotes: 3
Reputation: 1125
this compiles fine, so yes the ++iter is a valid statement. Incrementing is valid, jumping is not:
list<string> words;
void createList(string s)
{
istringstream iss(s);
string token;
while(getline(iss, token, ' '))
{
words.push_back(token);
}
}
string reverseWords(string s)
{
list<string>::iterator iter = words.begin();
string newString = "";
createList(s);
newString.append(*iter);
++iter;
for (; iter != words.end(); ++iter)
{
newString.append(" ");
newString.append(*iter);
}
return newString;
}
Upvotes: 1