In this code I try to move the iterator by 10 elements.
#include <iostream>
#include <string>
#include <vector>
int main()
{
using namespace std;
vector<int> v(20);
auto mid = v.begin() + 10;
cout<<mid;
}
On running this code, I get the error mentioned in the title.
I'm a beginner. I experience this error in almost every program I write. Where am I going wrong?
An iterator "points" to an element, what you want to be doing is:
cout << *mid;
You have to "dereference" the iterator to print what it points to. Trying to print it directly gives you the error you mentioned.
Edit: here's a little demo:
#include <iostream>
#include <vector>
int main(int argc, char* argv[])
{
std::vector<int> numbers;
numbers.push_back(4);
numbers.push_back(3);
numbers.push_back(2);
auto beg = numbers.begin();
auto mid = numbers.begin() + 1;
std::cout << *beg << std::endl;
std::cout << (beg < mid) << std::endl; // True because beg (index 0) points to an element earlier than mid (index 1)
std::cout << (*beg < *mid) << std::endl; // False because the element pointed-to by beg (4) is bigger than the one pointed-to by mid (3)
return 0;
}
Output
The first line shows 4 which is the value of the first element! The second line shows 1 (all non-zero values mean true) and the last line shows 0 (zero is the only value that means false).