c++ - Vector, iterators and const_iterator -
i have started learning vectors , iterators. can't understand 2 things. why can change constant iterator , role of "*"?
#include <iostream> #include <string> #include <vector> using namespace std; int main() { vector<string> inventory; inventory.push_back("inventory1"); inventory.push_back("inventory2"); inventory.push_back("inventory3"); vector<string>::iterator myiterator; vector<string>::const_iterator iter; cout << "your items:\n"; (iter = inventory.begin(); iter != inventory.end(); iter++) { cout << *iter << endl; }
when iter = inventory.begin()
makes iter
refer first string in vector. iter++
moves refer next string.
in output use *iter
way access string iter
refers to. in first output inventory1
.
the slight confusion constness
vector<string>::const_iterator iter;
is iterator refers things constant, while
const vector<string>::iterator iter;
would make iterator constant, allow modify object refers to.
Comments
Post a Comment