How do I iterate over a Constant Vector?

C++Visual C++

C++ Problem Overview


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

I want to iterate over the vector.

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

This is apparently illegal in C++.

Please help.

C++ Solutions


Solution 1 - C++

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

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
  */
}

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

Solution 2 - C++

Use const_iterator instead. An iterator allows modification of the vector, so you can't get one from a const container.

Also, the idiomatic way to write this loop uses it != students.end() instead of < (though this should work on a vector).

Solution 3 - C++

C++11 style:

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

Solution 4 - C++

Instead of vector<Student>::iterator, use vector<Student>::const_iterator.

Solution 5 - C++

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;
        }
    }

Solution 6 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionunj2View Question on Stackoverflow
Solution 1 - C++eq-View Answer on Stackoverflow
Solution 2 - C++Fred FooView Answer on Stackoverflow
Solution 3 - C++Shital ShahView Answer on Stackoverflow
Solution 4 - C++user511274View Answer on Stackoverflow
Solution 5 - C++Kirill V. LyadvinskyView Answer on Stackoverflow
Solution 6 - C++BlastfurnaceView Answer on Stackoverflow