开发者

a question in c++. just want a easy way to do this/

I have class

class A { int x; int y}

and

set<A> myset;

how can I iterate this set? I want to touch x, y variable in t开发者_运维知识库he class. Thank you


I want to touch x, y variable in the class.

In your class x and y are private. Members of classes are private by default. You can't just set x and y directly or else you'll get a compiler error. You need to provide a way to set x and y in the A's public interface, for example:

class A
{
int x; int y; // these are by default private
public:
   // set X
   void setX(int anX) {x = anX;}

   // set y
   void setY(int aY) {y = aY;}
};

// iterate over preexisting elements
set<A>::iterator iter;
for(iter = myset.begin(); iter != myset.end(); ++iter)
{
   iter->x = 5; // COMPILER ERROR, x is private
   iter->setX(5); //works, calls setter
   iter->setY(6); //works, calls setter

}

Another thing that prevents your set from working is the lack of an operator < for comparing to instances of A. set needs this to keep elements ordered and unique.

class A
{
   ...
   bool operator < (const A& other) const
   {
       // return true if this < other
       // up to you to define
   }
};


set<A>::iterator it;
for(it = myset.begin(); it != myset.end(); ++it)
{
    // your code
}

Alternatively you can use Boost::foreach:

BOOST_FOREACH(A& a, myset)
{
    // your code
}

EDIT: see comments :) all variables in A are declared as private, so there cannot be made any access. I guess there is no other way than to adjust the class and provide getters and setters or to make the member variables public.


set<A>::iterator myIterator;
for(myIterator = mySet.begin();
    myIterator != mySet.end();
    myIterator++)
{
 // do something
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜