开发者

list iterator problem in c++?

开发者 https://www.devze.com 2023-01-14 16:02 出处:网络
#include <iostream> #include <list> #include <string> using namespace std; // Simple example uses type int
#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 &l开发者_如何学Got;< " "; 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.

0

精彩评论

暂无评论...
验证码 换一张
取 消