I read another post that answered a question regarding iterators for vectors of pointers. I tried to use the same concept in my code but I receive some compilation errors. The code sample I was basing my code on is:
vector<c*> cvect;
cvect.push_back(new sc);
vector<c*>::iterator citer;
for(citer=cvect.begin(); citer != cvect.end(); citer++) {
(*citer)->func();
}
I want to use a similar concept to create a deep copy constructor for a class that has two data members that are vectors of pointers to objects. My code is similar to this:
class MyContainer {
vector<MyStuff*> vecOne;
vector<MyStuff*> vecTwo;
public:
MyContainer(const MyContainer& other);
};
MyContainer::MyContainer(const MyContainer& other) {
// copy vector one
vector<MyStuff*>::iterator vec1_itr;
for (vec1_itr = other.vecOne.begin(); vec1_itr != other.vecOne.end(); vec1_itr++) {
vecOne.push_back(new MyStuff(vec1_itr));
}
// copy vector two
vector<MyStuff*>::iterator vec2_itr;
for (vec2_itr = other.vecTwo.begin(); vec2_itr != other.vecTwo.end(); vec2_itr++) {
vecTwo.push_back(new MyStuff(vec2_itr));
}
}
I get some compilation errors like:
/path/MyContainer.cpp:38: error: no match for '
operator=
' in 'vec1_Itr = other->MyContainer::vecOne. std::vector<_Tp, _Alloc>::begin [with _Tp = MyStuff*, _Alloc = std::allocator<MyStuff*>]()
'candidates are:
__gnu_cxx::__normal_iterator<MyStuff*, std::vector<MyStuff, std::allocator<MyStuff> > >& __gnu_cxx::__normal_iterator<MyStuff*, std::vector<MyStuff, std::allocator<MyStuff> > >::operator=(const __gnu_cxx::__normal_iterator<MyStuff*, std::vector<MyStuff, std::allocator<MyStuff> > >&)
I also get an error for operator!=
... And another set of the same errors for the other vector.
Use a for loop and reference pointer In C++ , vectors can be indexed with []operator , similar to arrays. To iterate through the vector, run a for loop from i = 0 to i = vec. size() .
You can store pointers in a vector just like you would anything else. Declare a vector of pointers like this: vector<MyClass*> vec; The important thing to remember is that a vector stores values without regard for what those values represent.
The most obvious form of an iterator is a pointer. A pointer can point to elements in an array and can iterate through them using the increment operator (++).
You forgot to dereference the iterators. Try this instead:
vecOne.push_back(new MyStuff( **vec1_itr ));
Yes, should be double dereference (fixed above). And it should be the const_terator
instead since you are dealing with const
containing object:
vector<MyStuff*>::const_iterator vec1_itr;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With