结构向量和迭代C++11

Struct Vector and iteration C++11

本文关键字:C++11 迭代 向量 结构      更新时间:2023-10-16

我有一个简单的问题。根据其他例子,我的for迭代是正确的,但Eclipse给我带来了错误。。。我的功能

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

根据这个,我如何在常数向量上迭代?主题它应该工作,但它不是,我不知道为什么。当我改变整个std::vectro。。。自动工作!

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()循环:为什么循环条件中的iostream::eof被认为是错误的?

你真的应该这样做:

while(is >> day >> number >> time) {
    call.day = day;
    call.number = number;
    call.time = time;
    blng_.push_back(call);
}