/* strtok example */
#include <iostream>
#include <string>
#include<list>
using namespace std;
int main ()
{
list<string> read;
char str[] ="g 6 7 v 7 e 0 4 e 1 4 e 2 5 e 3 5 e 4 6 e 5 6";
char * pch;
pch = strtok (str," ");
while (pch != NULL)
{
read.push_back(pch);
pch = strtok (NULL, " ");
}
list<string>::iterator i;
i = read.begin();
i++;
int grid_x = stoi(*i++,nullptr,10);
int grid_y = stoi(*i++,nullptr,10);
i++;
int vertices = stoi(*i++,nullptr,10);
i++;
for(;i<read.end();)
{
cout<<*i++;
cout<<*i++;
i++;
}
return 0;
}
When my code gets into the for loop, it throws up an error saying that invalid operands to binary expression. I am doing a simple comparison to check if my iterator hasn't reached the end of the list. So, I am not sure as to why it is considering this comparison as invalid. Help on the same would be appreciated as I am new to STL and iterators.
std::list
does not support random access iterators. That is, i < read.end()
is not valid. You can test for equality: i != read.end()
, but you have to be a bit careful, because those increments could push the iterator past the end, and the ==
test would be meaningless.
Or you could use std::vector
instead of std::list
; that would make the <
test okay.
You'd be better off creating a stream object to parse that input, as I suggested in a comment to your earlier question.
You need to use !=
instead of <
for(; i != read.end();)
FYI, a while
loop would make more sense in this example:
while(i != read.end())
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.