簡體   English   中英

如何迭代常數向量?

[英]How do I iterate over a Constant Vector?

我有一個帶有字段名稱的Student向量。

我想遍歷向量。

void print(const vector<Student>& students)
    {
    vector<Student>::iterator it;
    for(it = students.begin(); it < students.end(); it++)
        {
            cout << it->name << endl;
        }
    }

在C ++中,這顯然是非法的。

請幫忙。

您有兩個(在C ++ 11中為三個)選項: const_iterator和索引(在C ++ 11中為+“ range-for”)

void func(const std::vector<type>& vec) {
  std::vector<type>::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
  */
}

您應該更喜歡使用!=而不是<與迭代器一起使用-后者不能與所有迭代器一起使用,前者可以。 使用前者,您甚至可以使代碼更通用(以便您甚至可以在不觸及循環的情況下更改容器類型)

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

const_iterator iterator允許修改vector ,因此您不能從const容器中獲得一個。

同樣,編寫此循環的慣用方式是使用it != students.end()而不是< (盡管它應在vector上工作)。

C ++ 11樣式:

void print(const vector<Student>& students) {
    for(auto const& student : students) {
            cout << student.name << endl;
    }
}

代替vector<Student>::iterator ,使用vector<Student>::const_iterator

void print(const vector<Student>& students)
    {
    vector<Student>::const_iterator it; // const_iterator
    for(it = students.begin(); it != students.end(); it++)
        {
            cout << it->name << endl;
        }
    }
void print(const vector<Student>& students)
    {
    for(auto it = students.begin(); it != students.end(); ++it)
        {
            cout << it->name << endl;
        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM