Hello guys,
Ive already ask similar question here but for some reason my brain cant understand this thing :S Im not good with talking will just wrote a code example.
You really should provide a small complete program that illustrates your problem.
The problem with the line you highlighted is that y is an iterator not an integer, index values must be an integral type.
Try:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
for(size_t y = 0; y < Vec.size(); ++y)
{
if(Vec[y].ID > 0)
// Do something.
}
// Or
for( auto y = Vec.begin(); y != Vec.end(); y++ )
{
if( y->ID > 0 )
// Or
for( auto y : Vec)
{
if( y.ID > 0 )//Here is the problem
{
//Do something
}
}
for( int i = 0; i < Vec.size(); i++ )
{
cout << Vec[i].Name << endl;
}
When I was learning vectors someone says that begginning of the vector isnt 0 it is Vec.begin(). Thats why I was trying to use that. But I guess its not true. I used simple int and made assumption that first element has ID of 0 and it works. So I basicly did what jbl wrote in his first example. For me this way is the easier in logic sense for beginners like me. When it is better to use iterators and "->" operator then simple [] operator?
EDIT:
why size_t instead of simple int?
If you were using a different container type instead of a vector, then the [] operator may not be applicable.
Let's say the std::vector is replaced by a std::list, these will still work:
1 2 3 4 5 6 7 8 9 10
void Function( const list<Structure> &Vec)
{
for ( auto y = Vec.begin(); y != Vec.end(); y++ )
{
if ( y->ID > 0 )
{
cout << y->name << endl;
}
}
}
1 2 3 4 5 6 7 8 9 10
void Function( const list<Structure> &Vec)
{
for ( auto y : Vec )
{
if ( y.ID > 0 )
{
cout << y.name << endl;
}
}
}
Edit:
why size_t instead of simple int?
size_t is an integer. It is unsigned, so will avoid compiler warnings as Vec.size() is also unsigned. It is also guaranteed to be wide enough for the task (integers come in different widths: short, long, long long etc).