Checking the status of a member of a class for various objects

For instance I create a class having one member of type bool and 100 objects.
Now if I want to perform certain actions with those objects that have their member as true, do I have to perform the action separately for each object, or is there a way to perform that action collectively.
In other words is there a way to:
Check the values of all the objects of a class, and for those that are true, perform certain actions?
Sure there is...
foreach(obj,objects)if (obj.isMemberTrue())obj.performAction();
If I create a
1
2
3
4
5
6
class IsTrue
{
public:
     bool A;
     int x;
}obj1, obj2 /*until obj100...*/;



Now if I want the program to check if obj1.A = true And if it is, set obj.x = 1 and do so for all the other objects. Is there a way to do that?
1
2
3
4
5
6
7
8
9
10
class IsTrue
{
public:
     bool A;
     int x;
};
IsTrue objects[100];

[...]
for (auto& obj : objects)if (obj.A)obj.x=1;


This requires C++0x support. If that is not available, you can use Boost.Foreach instead.
Nisheeth wrote:
Now if I want to perform certain actions with... objects..., do I have to perform the action separately for each object, or is there a way to perform that action collectively.
The instances of a class are only stored in the variables you tell them to be stored in. So in short, no. There is no short cut way to access all the instances as a collection, unless you designed your class that way. Example:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
#include <iostream>
#include <vector>
#include <assert.h>

using namespace std;


class IsTrue {
	static vector<IsTrue*> instances;
	bool a;

 public:
	IsTrue(bool b = false) : a(b) {
		instances.push_back(this);
	}
	
	~IsTrue() {
		//linear search, for *this in the vector instances
		int pos = -1;
		for( int i = 0; i < instances.size(); i++ )
			if( instances[i] == this ) {
				pos = i;
				break;
			}
		assert( pos >= 0 );
		instances.erase( instances.begin() + pos );
	}
	
	bool getA() const {
		return a;
	}
	
	void setA(bool b) {
		a = b;
	}
	
	static void setAllA(bool b) {
		for( int i = 0; i < instances.size(); i++ )
			instances[i]->a = b;
	}
};

vector<IsTrue*> IsTrue::instances;


ostream& operator<<(ostream &out, const IsTrue &t) {
	return cout << '(' << (t.getA() ? "true" : "false") << ')';
}


int main() {
	IsTrue t, u, v, w, x;
	cout << t << u << v << w << x << endl;
	
	t.setA(true);
	w.setA(true);
	cout << t << u << v << w << x << endl;
	
	IsTrue::setAllA(true);
	cout << t << u << v << w << x << endl;
	
	return 0;
}
(false)(false)(false)(false)(false)
(true)(false)(false)(true)(false)
(true)(true)(true)(true)(true)
Last edited on
Topic archived. No new replies allowed.