I am relatively new to C++,
I have two pieces of code:
for (std::vector<int>::size_type i = 0; i != inventoryvec.size(); i++)
{
cout << inventoryvec[i].description << endl;
}
and
for (std::vector<items>::iterator it = inventoryvec.begin(); it != inventoryvec.end(); ++it)
{
cout << inventoryvec[it].description;
}
The second code is not valid "Error no operator "[]" matches these operands" - why am I unabled to use "it" in the same way I use "i". It main purpose it to represent a value right?
Is this a limitation of using the iterator over indices or am I just doing something wrong.
To dereference a vector use the *
operator.
Replace inventoryvec[it]
with (*it)
.
Of course, like usual, you can use it->description
as shorthand for (*it).description
.
Iterators are just abstract pointers. An iterator points to a member. You dereference it with *
(or you can use use ->
), advance it with ++
, and move it one item back (if that operation is implemented) with --
.
In the case of vectors, there's virtually no abstraction. Vector iterators are (or can be) (with the exception of specializations) literally pointers to the members of the array that std::vector
wraps.
You can think of std::vector<items>::iterator
as a pointer of items
type but more complicated. Thus, you use the dereference operator (aka *) to access the data to which it points. You can use ->
operator as well
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.