Mar 15, 2014 at 1:53pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13
#include <iostream>
bool contain(const std::string& s, char c)
{
return s.find(c) != std::string::npos;
}
int main()
{
char c;
std::cin >> c;
std::cout << contain("YyNn" , c);
}
Or if you want generality and use something aside from chars in the future:
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
#include <unordered_set>
#include <iostream>
#include <vector>
#include <algorithm>
template <typename T>
bool contain(const std::unordered_set<T>& C, T val)
{
return C.find(val) != C.cend();
}
template <class T, typename V>
bool contain(const T& C, V val)
{
return std::find(C.cbegin(), C.cend(), val) != C.cend();
}
int main()
{
std::unordered_set<char > booleans {'Y' , 'y' , 'N' , 'n' };
std::vector<int > ints{1, 3, 4, 7};
char c;
std::cin >> c;
int i;
std::cin >> i;
std::cout << contain(booleans, c) << '\n' <<
contain(ints, i);
}
Last edited on Mar 15, 2014 at 2:03pm UTC
Mar 15, 2014 at 1:59pm UTC
What about dealing with integer?
1 2 3 4
int x;
std::cin >> x;
if ( (x == 1) || (x == 3) || (x == 7) )
std::cout << "You win\n" ;
How can I rewrite line 3?
Last edited on Mar 15, 2014 at 2:01pm UTC
Mar 15, 2014 at 2:04pm UTC
I have updated my post. You can use those templated helper functions to find if value is contained inside any STL container
Mar 15, 2014 at 2:24pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <initializer_list> // http://en.cppreference.com/w/cpp/utility/initializer_list
template < typename T, typename U >
bool in( const T& value, const std::initializer_list<U>& set )
{
for ( auto & v : set ) if ( v == value ) return true ;
return false ;
}
int main()
{
char ch ;
std::cin >> ch ;
if ( in( ch, { 'Y' , 'y' , 'N' , 'n' } ) ) std::cout << "ok\n" ;
int i = 7 ;
if ( in( i, { 1, 3, 5, 7, 9 } ) ) std::cout << "ok\n" ;
}
http://coliru.stacked-crooked.com/a/f51a430930def92c
Last edited on Mar 15, 2014 at 2:26pm UTC
Mar 15, 2014 at 2:59pm UTC
This seems even more complicated than simply typing all possibility.
So is there no easy approach which I can do this by a few code?
Mar 15, 2014 at 3:10pm UTC
Last edited on Mar 15, 2014 at 3:14pm UTC