Can someone tell me what I am doing wrong here?
Code:void print(const std::vector<int>& vec)
{
for ( std::vector<int>::iterator itr = vec.begin(), end = vec.end(); itr != end; ++itr )
{
std::cout << *itr << std::endl;
}
}
Printable View
Can someone tell me what I am doing wrong here?
Code:void print(const std::vector<int>& vec)
{
for ( std::vector<int>::iterator itr = vec.begin(), end = vec.end(); itr != end; ++itr )
{
std::cout << *itr << std::endl;
}
}
Yes, your problem is that constant references to a vector object should be using constant things. There is something called const_iterator for vector, and any other STL container, in this situation.
If you are using C++11, then this...
for ( std::vector<int>::iterator itr = vec.begin(), end = vec.end(); itr != end; ++itr )
...can become...
for ( auto itr = vec.begin(), end = vec.end(); itr != end; ++itr )
(Note how this code works whether or not your object is const or not1)
...or even...
Code:for (const auto & item : vec)
std::cout << item << std::endl;
Thanks Elysia!
I actually just read the article on C++11 today on this site, I am definitely interested in researching more into it as it seems to have enabled a lot of easier coding. For now, I am still a beginner trying to gather more experience in coding. :)
Currently trucking my way through this sites exercises as I just finished reading the "Jumping into c++" book which was actually the first c++ book I've gone through that organized the learning process in a way that seems smart to me. Perhaps that is just the rookie in me talking, but it was a great read and easy to step through the learning the way it was organized.