在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; 
} 

如果我使用上述程序,并且将string test=*i更改为cout << *i << " ";,它将无法正常工作。这有什么问题?在C++中列表迭代器问题?

+2

这里没有问题(除了'int main()')。代码工作并按预期输出所有内容。你需要最终解决某个版本的代码,因为当它一直在变化时,它是不可能回答的。 – AnT 2010-09-04 07:17:20

+2

@AndreyT啊,这是这里烦人的事情之一,你回答原来的问题,问题得到改变,然后有人低估你不回答这个问题。 /捂脸。 – 2010-09-04 08:14:02

+0

raj,我倾向于投票结束。下定决心,提出一个实际问题。该程序,似乎正在做它应该做的:http://codepad.org/K3qh8oC4 – sellibitze 2010-09-04 13:05:51

这甚至不应该编译(在最近的g ++中它不会)。

ilist<int>的迭代器,因此*i的类型为int。如果分配此为string这样的:

string test=*i; 

编译器会寻找一个转换,从intstring。标准库中没有定义这种转换。

您最后一次循环尝试将字符串测试设置为整数的值。

您应该试试cout < < * i < < endl;

+1

对不起,这是我的错误,我已经改变了程序..dll相同的错误? – raj 2010-09-04 07:04:14

+0

你可能会试着将int读入一个临时的int变量int myInt = * i; cout 2010-09-04 07:08:57

+0

你能告诉我们错误信息是什么吗?它是来自编译器还是你没有得到任何输出? – 2010-09-04 07:12:16

这对我的作品并产生输出:

testtestingggggexample 

你缺少单词和endl末之间的空间,但输出是有正如人们所期望的那样。

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

为我工作。我得到这个输出

testtestingggggexample

我在SUSE G ++ 3.4.3版本。