sci wrote:
class A;
void function(vector <A>* l)
{
...
}
main(){
vector<A> aAList;
function(&aALis t[0]);
}
How to pass address of aAlist object into a function?
Should be:
int main()
{
vector<A> aAList;
function(&aALis t);
return 0;
}
&aAList[0] returns the address of the first element in aAList, not the
address of the vector.
Otherwise, you got it right, pretty much. If you don't intend to change
the vector in "function", you should use "const vector<A>*" instead of
"vector<A>* ".
How to call each member inside "function() "?
To call the vector's functions, you have options:
(*l).size()
//or
l->size()
To access the elements of the vector you have the similar options. To
access element i:
(*l)[i]
//or
l->at(i)
You can also use iterators:
vector<A>::cons t_iterator begin = l->begin();
vector<A>::cons t_iterator end = l->end();
do_something(be gin, end);
Can a list be passed the same way like a vector?
Yes:
list<A> aAList;
function(&aALis t);
void function(const list<A>* l)
{
//...
}
Or, if you want to change the list:
void function(list<A >* l)
{
//...
}
Is it possible to pass a reference to "aAList" into the "function() "?
Yes, and it is much preferred actually. You should avoid using pointers
unless you have to:
class A;
void function(const vector<A>& l)
{
//...
}
int main()
{
vector<A> aAList;
function(aAList );
return 0;
}
Inside function, you don't need any fancy dereferencing:
l.size()
l[i]
l.at(i)
vector<A>::cons t_iterator begin = l.begin();
vector<A>::cons t_iterator end = l.end();
do_something(be gin, end);
But more importantly, you don't have to worry about null pointers. Once
again, if you have to change the vector in function, don't use const:
void function(vector <A>& l)
{
//...
}
mark