2010-09-04 101 views
-1
#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

回答

1

這甚至不應該編譯(在最近的g ++中它不會)。

ilist<int>的迭代器,因此*i的類型爲int。如果分配此爲string這樣的:

string test=*i; 

編譯器會尋找一個轉換,從intstring。標準庫中沒有定義這種轉換。

1

您最後一次循環嘗試將字符串測試設置爲整數的值。

您應該試試cout < < * i < < endl;

+1

對不起,這是我的錯誤,我已經改變了程序..dll相同的錯誤? – raj 2010-09-04 07:04:14

+0

你可能會試着將int讀入一個臨時的int變量int myInt = * i; cout << myInt << endl; – 2010-09-04 07:08:57

+0

你能告訴我們錯誤信息是什麼嗎?它是來自編譯器還是你沒有得到任何輸出? – 2010-09-04 07:12:16

1

這對我的作品併產生輸出:

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$ 
1

爲我工作。我得到這個輸出

testtestingggggexample

我在SUSE G ++ 3.4.3版本。