문제

this is what im doing, im getting some info from a .txt file those are numbers of course when im getting them i get them as strings in a list of strings...(i know it could be chars but in this example is strings) so when im inserting them on another list it should be something like this

list<int> l;

//i is the iterator for the 1st list that already has all the strings
l.push_back(atoi(*i.c_str()));

i cant use c_str() because i is trying to access the elements of the list is there anyway i can do this?

basically what im trying to do is just getting my strings from one list and change them to integers while keeping the list format

any help would be really appreciated thank you

도움이 되었습니까?

해결책

You need (*i).c_str() or i->c_str().

You probably want to do the job as a whole a bit differently, specifically in a way that doesn't require you to deal directly with iterators at all. For example, let's assume what you have is:

list<string> strings;
list<int> ints;

Then I'd almost certainly do the job with std::transform, probably something like this:

std::transform(strings.begin(), strings.end(), std::back_inserter(ints),
    [](std::string const &in) { return atoi(in.c_str()); });

or:

transform(begin(strings), end(strings), std::back_inserter(ints),
          [](string const &in) { return stoi(in); });

In case you're not familiar with it, that last line is a lambda (new with C++11). Assuming you're using a fairly new compiler (e.g., gcc 4.7.x or newer, VC++ 2010 or newer) it shouldn't be a problem.

I'd also seriously consider using std::vector instead of std::list. I've virtually never found std::list to be a particularly good choice. Even situations that should theoretically favor a linked list usually don't, at least in my experience.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top