2015-04-06 102 views
-2

我有一個簡單的問題。根據其他的例子我迭代是正確的,但Eclipse中拋出我的錯誤... 我的功能結構向量和迭代C++ 11

billing::billing(std::istream &is) { 
    unsigned day; 
    std::string number; 
    float time; 
    struct call call; 
    while (!is.eof()) { 
     is >> day >> number >> time; 
     call.day = day; 
     call.number = number; 
     call.time = time; 
     blng_.push_back(call); 
    } 
    for(std::vector<call>::const_iterator it; it = blng_.begin(); it != blng_.end(); ++it) 
     // THROWS HERE ERRORS! 
     std::cout << it->day << std::endl; 
} 

編譯之後,他拋出了我類似的東西

expected a type, got 'call' billing.cpp  
'it' was not declared in this scope billing.cpp 
expected ';' before 'it' billing.cpp 
expected ')' before ';' token billing.cpp 
invalid type in declaration before 'it' billing.cpp 
template argument 2 is invalid billing.cpp 
the value of 'call' is not usable in a constant expression billing.cpp 
type/value mismatch at argument 1 in template parameter list for   
'template<class _Tp, class _Alloc> class std::vector' billing.cpp 

根據這一How do I iterate over a Constant Vector?話題應該是工作,但它不是,我沒有freq想法爲什麼。當我改變這整個std :: vectro ...到汽車它的作品!

+3

你去了,創建了一個名爲'call'對象,隱藏式的名稱。 – juanchopanza

+0

啊,你是對的!我看了上千次,找不到它。 – FilOle

回答

1

C++11你可以重寫:

for(std::vector<call>::const_iterator it = blng_.begin(); it != blng_.end(); ++it) 
    std::cout<<it->day<<std::endl;; 

for(const auto& c: blng_) 
    std::cout << c.day << std::endl; 

附加說明:

你永遠不應該有eof()循環: Why is iostream::eof inside a loop condition considered wrong?

你真的應該做這樣的事情:

while(is >> day >> number >> time) { 

    call.day = day; 
    call.number = number; 
    call.time = time; 
    blng_.push_back(call); 
} 
+0

噢,我是把部分代碼翻譯成英文,並將其複製錯誤。但問題是如上所述的juanchopanza。不管怎麼說,還是要謝謝你! :)我很喜歡最後一個! Galik嗯,感謝EOF注意我會馬上閱讀! – FilOle