简体   繁体   中英

list iterator problem in c++?

#include <iostream>
#include <list>
#include <string>
using namespace std;

// Simple example uses type int

main()
{
   list<string > L;
   L.push_back("test");              // Insert a new element at the end

 L.push_back("testinggggg"); 
 L.push_back("example"); 
   list<string>::iterator i;

   for(i=L.begin(); i != L.end(); ++i) {
       string test = *i;
       cout << test;
   }
   return 0;
}

I am not getting any output if I use the above program and if I change the string test=*i to cout << *i << " "; it works. What is the problem with this?

This should not even compile (and it doesn't, on a recent g++).

i is an iterator over a list<int> , so *i is of type int . If you assign this to a string like this:

string test=*i;

the compiler will look for a conversion from int to string . There is no such conversion defined in the standard library.

Your last for loop you attempt to set the string test to the value of an integer.

You should just try cout << *i << endl;

It works for me and produces the output:

testtestingggggexample

You're missing spaces between the words and an endl at the end, but the output is there as one would expect.

jkugelman$ g++ -Wall -o iterator iterator.cpp 
iterator.cpp:8: warning: ISO C++ forbids declaration of ‘main’ with no type
jkugelman$ ./iterator 
testtestingggggexamplejkugelman$ 

Working for me. I got this output

testtestingggggexample

I am on Suse g++ 3.4.3 version.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM