开发者

How to handle multiple members of a C++ class simultaneously?

I'm used to Python, and struggling to learn some C++. In Python, when I have a class with a "move" function, I can simply add its members to a list and iterate over the list like this:

for i 开发者_JS百科in list:
    i.move(n)

Now, how is the corresponding thing done conveniently in C++?


You can do the same in C++ by using pointers or reference to your objects.

If your class is MyClass, you could declare:

std::vector<MyClass*> list;

then add your objects to the list:

list.push_back(&objectOfMyClass); //-- for all of your objects

and finally:

std::vector<MyClass*>::iterator itr;
for (itr = list.begin(); itr != list.end(); ++itr) {
   (*itr)->myMethod(...);
}

I have used std::vector for simplicity in allocating objects (it grows automatically) and to get an iterator, which should be known to you, but you could do the same just by using a plain array, if you prefer.


You can get your python like syntax using boost foreach

Since you probably want to use virtual functions this means you will have objects of different types in your container. This means you need a container of pointers, so we go to boost again fro boost::ptr_vector (ptr_list works the same way).

Then we can get a simple application like this:

#include <boost/foreach.hpp>
#include <boost/ptr_container/ptr_vector.hpp>

#define   foreach   BOOST_FOREACH

class MyBase {public: virtual ~MyBase() {} virtual void move(int x) = 0;}

int main()
{
    boost::ptr_vector<MyBase>    data  /*= fillData()*/;

    foreach(MyBase& i, data)
    {
         i.move(4);
    }  
}


//create a vector of int's (basically a container, like an array)
vector<int> v;
//insert item into vector    
v.push_back(12);

//create an iterator that points to the first item in the vector    
vector<int>::iterator iter = v.begin();


// move through the vector from begin() to end(), printing each item to console.    
for (; iter != v.end(); iter++)
{
    std::cout << *iter;
}


Try

list<myobj>::iterator Iterator;
for(Iterator = mydata.begin(); Iterator != mydata.end(); Iterator++)
 {
  (*Iterator).move(n);
 }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜