post  Change condition

bananaHUNT (10)   Link to this post
How would you do something like this:

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

if ( a )
{ ... }
Bazzy (4111)   Link to this post
Can you explain a bit more?
bananaHUNT (10)   Link to this post
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
computerquip (877)   Link to this post
I think he means that he doesn't know what you want. It sounds like your solving your own problem.
bananaHUNT (10)   Link to this post
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
Bazzy (4111)   Link to this post
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
bananaHUNT (10)   Link to this post
But then I still have the "cout << .." part twice, no?
jsmith (3802)   Link to this post
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 );


Bazzy (4111)   Link to this post
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

This topic is archived - New replies not allowed.