Change condition

closed account (iA5S216C)
How would you do something like this:

if ( bool_a )
{ a = condition; }
else { a = !condition; }

if ( a )
{ ... }
Can you explain a bit more?
closed account (iA5S216C)
for example in a document there's a list of people who own a cat (marked by a bool).
the user will input if he wants to view the people with cats, or the people without cats:

..
if ( show_people_with_cats )
{ a = people[t].cat; }
else
{ a = !people[t].cat; }
for ( t = 0 ; t < number_of_people ; t++)
{ if ( a ) { cout << people[t].name } }

like that

yes i realize that i can put " if ( people[t].cat ) { cout << ..} " ánd " if ( !people[t].cat ) { ..} "
but then i would have the " cout << .. " part twice.
Last edited on
closed account (S6k9GNh0)
I think he means that he doesn't know what you want. It sounds like your solving your own problem.
closed account (iA5S216C)
Well mine is not really a solution. "a = people[t].cat " doesn't work. What variable would 'a' be? A string won't work because if (..) requires a bool. And a bool won't work because I need the program to check either "people[t].cat" or "!people[t].cat" for each person in the for (..) loop.

Basically I want the condition(a) of the second if (..) (the one in the for(..) loop) to be dependant on if the user wants to view the persons with cat, or without.
Last edited on
You need only a if inside the for:
display a person if the user wants to see people with cat and that person has one, or when the user wants to see people with no cats and the person doesn't have one
closed account (iA5S216C)
But then I still have the "cout << .." part twice, no?
I don't think there is a language-specific thing that will do what you want. But you can design a solution.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
template< typename Iter, typename Comp, typename Fn >
void for_all_that( Iter first, Iter last, Comp comp, Fn fn )
{
    for( ; first != last; ++first )
        if( comp( *first ) )
            fn( *first );
}

bool has_cat( const Person& p ) {
    return p.cats > 0;
}

bool has_no_cats( const Person& p ) {
    return !has_cat( p );
}

void print( const Person& p ) {
    cout << p.name;
}

// Assuming people is an array..., otherwise for STL container
// use people.begin() and people.end()
for_all_that( people, people + number_of_people, 
    show_people_with_cats ? &has_cat : &has_no_cats, &print );


You would need a logical nxor to have a single cout
eg:
1
2
3
4
5
6
7
8
9
10
11
12
13
bool nxor ( bool a, bool b )
{
    return ! ( a ^ b ) ;
}

//...

for ( t = 0 ; t < number_of_people ; t++ )
{
    if ( nxor ( show_people_with_cats, people[t].cat ) )
         cout << people[t].name;
}

Last edited on
Topic archived. No new replies allowed.