Click here to Skip to main content
15,885,875 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi I am new to C++
I have a vector iterator It, which has a Class A inside it and class has double variable b.
I need to access the variable so I wrote something like this:
It.A->b
but its throwing me different errors.
can someone tell me the correct format?
Posted

You need to dereference the iterator. What you want is

C++
*It->b


[rev.1 - sorry, syntax error, hopefully fixed...]
 
Share this answer
 
v2
Comments
diasblood 15-Jul-13 0:40am    
it gives an error on *It (Expression must have pointer to class type)
diasblood 15-Jul-13 0:48am    
still same error on It
H.Brydon 15-Jul-13 0:59am    
Try this:

A* ptr = *It;
double x = ptr->b;

This should be the same as

double x = *It->b;

with extra layers of unrolling the onion.
diasblood 15-Jul-13 10:21am    
the first solution worked. I was missing a function call earlier.
Thanks a lot
Just as a remark, I would not use an iterator with a vector, but just use the index. For example:
C++
    std::vector<double> vec;
    ...
    double d = vec[i];
</double>

If you insist in using an iterator, then think of it as being kind of a pointer (syntax wise), and hence you would dereference it as:
C++
    std::vector<mystruct> vec;
    ...
    MyStruct* p = it;
    ... or if age is a member of MyStruct
    int age = it->age;
</mystruct>
 
Share this answer
 
Comments
H.Brydon 15-Jul-13 12:16pm    
There should be no problem using an iterator on vector<whatever>. This type of sequential access is supposed to be (slightly) faster than an index lookup in a loop, even for vector<>.
nv3 15-Jul-13 14:21pm    
I wasn't worried about performance, as todays's optimizer will probably produce equally efficient code for both cases. But a simple loop over an integer index is in my opinion easier to write and to understand than the somewhat typing intensive iterator syntax. -- Just a matter of taste I guess.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900