I understand that using const
and &
and all the other fancy C++ stuff is to, as I heard Bjarne Stroustrup say in a video, "help the compiler." I understand how using &
(references) whenever possible can help make the program more efficient, but one thing I don't understand is how const_iterator
helps at all. Suppose I use
#include <string>
#include <iostream>
int main()
{
const std::string s = "Vote for Pat Buchanan in 2016";
for (std::string::const_iterator i1(s.cbegin()), i2(s.cend()); i1 != i2; ++i1)
std::cout << *i1 << std::endl;
return 0;
}
instead of
#include <string>
#include <iostream>
int main()
{
const std::string s = "Vote for Pat Buchanan in 2016";
for (std::string::iterator i1(s.begin()), i2(s.end()); i1 != i2; ++i1)
std::cout << *i1 << std::endl;
return 0;
}
Both are valid. How would the former be more efficient? How does iterating through a string with a const_iterator
go any faster than iterating through a string with a regular iterator
? Aren't they the same data structure? Why would you need separate data structures for iterating through a container that is constant throughout a program, as opposed to iterating through a container that is non-constant?
For instance, if I wrote my own string class StringCool
that used nodes
node
{
char c;
node * next, * previous;
}
to iterate through it, I don't see why I would need a different kind of node to iterate through constant instances of StringCool
. The only thing different about the constant version of a StringCool
instance is that the class would disallow writing. I could give it a node with fields
const char c;
const node * next, * previous;
but I don't see how iterating through a linked list of such nodes would be any faster.
Related question:
When creating classes in C++, is it possible to define what happens when an instance of the class is declared const
?