Puoi anche fare a meno degli "if":
codice:
/*
Isidoro Ghezzi, 2 feb 2010
$ g++ --version; g++ -ansi -pedantic -Wextra -Wconversion main.cpp; ./a.out
i686-apple-darwin8-g++-4.0.1 (GCC) 4.0.1 (Apple Computer, Inc. build 5367)
Copyright (C) 2005 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
The number -5 is less than 1;
The number 0 is less than 1;
The number 1 is between 1 and 10;
The number 2 is between 1 and 10;
The number 10 is between 1 and 10;
The number 2010 is greater than 10;
*/
#include <iostream>
#include <algorithm>
namespace ig{
void TestNoSwitchAndIf (const int theSelector){
const char * kCStringContainer []={
"less than 1",
"between 1 and 10",
"greater than 10"
};
const unsigned short aIndex = (theSelector >= 1) + (theSelector > 10);
std::cout << "The number " << theSelector <<
" is " << kCStringContainer [aIndex] << ";" << std::endl;
}
}
int main (void){
const int kTestContainer []={
-5, 0, 1, 2, 10, 2010
};
std::for_each (kTestContainer,
kTestContainer + sizeof (kTestContainer)/sizeof (kTestContainer [0]),
ig::TestNoSwitchAndIf
);
return 0;
}
;-)