How do I iterate over a Constant Vector?

后端 未结 6 923
终归单人心
终归单人心 2020-12-02 22:16

I have a vector of Student which has a field name.

I want to iterate over the vector.

void print(const vector& students)
    {
            


        
6条回答
  •  佛祖请我去吃肉
    2020-12-02 22:44

    You have two (three in C++11) options: const_iterators and indexes (+ "range-for" in C++11)

    void func(const std::vector& vec) {
      std::vector::const_iterator iter;
      for (iter = vec.begin(); iter != vec.end(); ++iter)
        // do something with *iter
    
      /* or
      for (size_t index = 0; index != vec.size(); ++index)
        // do something with vec[index]
    
      // as of C++11
      for (const auto& item: vec)
        // do something with item
      */
    }
    

    You should prefer using != instead of < with iterators - the latter does not work with all iterators, the former will. With the former you can even make the code more generic (so that you could even change the container type without touching the loop)

    template
    void func(const Container& container) {
      typename Container::const_iterator iter;
      for (iter = container.begin(); iter != container.end(); ++iter)
        // work with *iter
    }
    

提交回复
热议问题