结构向量和迭代C ++ 11

时间:2015-04-06 21:47:25

标签: c++ c++11 vector struct iteration

我有一个简单的问题。根据其他示例,我的迭代是正确的,但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

根据这个How do I iterate over a Constant Vector?主题,它应该有效,但事实并非如此,我没有想到为什么。当我将整个std :: vectro改为自动时,它可以工作!

1 个答案:

答案 0 :(得分: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);
}