That two for loop is the same
The 1st loop, I manually use const_iterator but I didnt use any constant reference to my vector? So how does the compiler deduce to this type?
And if you will read article, please not that it is outdated: in C++11 standard library was fixed and allows usage of const_iterators in all sensible places. In Effective Modern C++ Scott Meyers now advises to use const_iterators if possible and discuss changes made in C++11 (Item 13)
OW no no. I merely put it to show that the compiler is okay with const_iterator rather that iterator only. Putting auto makes it const_iterator. It was just for illustration. My concern is how and why does compiler go to const_iterator even if my vector isnt constant
#include <iostream>
struct A
{
constint c = 45 ; // always const
int i = 67 ; // const in const A, non-const in non-const A
mutableint m = 92 ; // never const
void foo() const ; // operates on an object of type const A
void bar() ; // operates on an object of type (non-const) A
};
void test_it( const A* ) { std::cout << "pointer to const A\n" ; }
void test_it( A* ) { std::cout << "pointer to (non-const) A\n" ; }
void test_it( const A& ) { std::cout << "const A\n" ; }
void test_it( A& ) { std::cout << "(non-const) A\n" ; }
void test_it( constint& ) { std::cout << "const int\n" ; }
void test_it( int& ) { std::cout << "(non-const) int\n" ; }
#define TEST_IT(x) { std::cout << #x ":\t" ; test_it(x) ; }
void A::foo() const
{
std::cout << "A::foo() const => " ;
TEST_IT(this) ;
}
void A::bar()
{
std::cout << "A::bar() (non-const) => " ;
TEST_IT(this) ;
}
void baz( const A& ca, A& a )
{
TEST_IT(ca) ; // ca: const A
TEST_IT( ca.c ) ; // ca.c: const int
TEST_IT( ca.i ) ; // ca.i: const int
TEST_IT( ca.m ) ; // ca.m: (non-const) int
std::cout << "ca.foo() => " ; ca.foo() ; // ca.foo() => A::foo() const => this: pointer to const A
std::cout << "\n\n" ;
TEST_IT(a) ; // a: (non-const) A
TEST_IT( a.c ) ; // a.c: const int
TEST_IT( a.i ) ; // a.i: (non-const) int
TEST_IT( a.m ) ; // a.m: (non-const) int
std::cout << "a.foo() => " ; a.foo() ; // a.foo() => A::foo() const => this: pointer to const A
std::cout << "a.bar() => " ; a.bar() ; // a.bar() => A::bar() (non-const) => this: pointer to (non-const) A
}
int main()
{
A a ;
baz( a, a ) ;
}
clang++ -std=c++14 -stdlib=libc++ -O2 -Wall -Wextra -pedantic-errors -Wno-unused-parameter main.cpp -lsupc++ && ./a.out
ca: const A
ca.c: const int
ca.i: const int
ca.m: (non-const) int
ca.foo() => A::foo() const => this: pointer to const A
a: (non-const) A
a.c: const int
a.i: (non-const) int
a.m: (non-const) int
a.foo() => A::foo() const => this: pointer to const A
a.bar() => A::bar() (non-const) => this: pointer to (non-const) A