I am using a for-loop to access and print values in a vector (v). The for-loop uses a random access iterator variable starting from v.beginning and and ending before v.end.
#include<iostream>
#include<vector>
using namespace std;
int main(){
vector<int> v;
/* create initializer list */
auto inList = {1, 2, 3, 4, 5};
//EDIT
//Works
vector<int> vect1;
vect1.assign(5,100);
for(auto it=vect1.begin(); it<vect1.end();it++){
cout<<*it<<endl;
}
//Works
for(auto it=v.begin(); it!=v.end();it++){
cout<<*it<<endl;
}
return 0;
// Edit: seems to work now.
for(auto it=v.begin(); it<v.end();it++){
cout<<*it<<endl;
}
// Doesn't Work (ERROR MARKERS Correspond to the following loop)
for(int it=v.begin(); it!=v.end();it++){
cout<<*it<<endl;
}
return 0;
}
Observation: When i try to change the type from 'auto' to 'int', i receive the following error:
- mismatched types 'const std::reverse_iterator<_Iterator>' and 'int'
- mismatched types 'const std::fpos<_StateT>' and 'int'
- mismatched types 'const std::pair<_T1, _T2>' and 'int'
- cannot convert 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*, std::vector<int> >}' to 'int' in initialization
- no match for 'operator!=' (operand types are 'int' and 'std::vector<int>::iterator {aka __gnu_cxx::__normal_iterator<int*,
std::vector<int> >}')
- mismatched types 'const __gnu_cxx::__normal_iterator<_IteratorL, _Container>' and 'int'
- mismatched types 'const __gnu_cxx::__normal_iterator<_Iterator, _Container>' and 'int'
- mismatched types 'const std::vector<_Tp, _Alloc>' and 'int'
- mismatched types 'const __gnu_cxx::new_allocator<_Tp>' and 'int'
- mismatched types 'const std::istreambuf_iterator<_CharT, _Traits>' and 'int'
- mismatched types 'const _CharT*' and 'int'
- mismatched types 'const std::__cxx11::basic_string<_CharT, _Traits, _Alloc>' and 'int'
- mismatched types 'const std::allocator<_CharT>' and 'int'
- mismatched types 'const std::move_iterator<_Iterator>' and 'int'
Also, when i revert to change the type of the 'it' variable to 'auto' and change the stopping condition of the for loop from '!=' to < then it doesn't work, although cpp reference says that the "<" operator it is supported.
Questions
1) Why does my iterator variable have to be type 'auto' for the .begin() and .end() functions?
2) why cant i use '<' logical operator with the iterator variable?