Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ comparing bunch of values with a given one

Tags:

c++

I need to compare one given value with a retrieved values. I do this several times in the code. I am not satisfied with how it looks and I am seeking for a some sort of an util function. Anyone wrote one?

Number of values I am comparing with is known at the compile time.

Update: I'd like to get rid of containers as I know exact amount of values ( often not more then 3 ) I want to compare with. And it is not so convenient to put items to the container every time.
I don't love if neither because it is not obvious as "find".

#include <algorithm>
#include <string>
#include <vector>

std::string getValue1()
{
    return "test";
}

std::string getValue2()
{
    return "the";
}

std::string getValue3()
{
    return "world";
}

int main()
{
    const std::string value = "the";

    // simple if
    if ( value == getValue1() ||
         value == getValue2() ||
         value == getValue3() )
        return 1;

    // using collections like vector, set
    std::vector<std::string> values;
    values.push_back( getValue1() );
    values.push_back( getValue2() );
    values.push_back( getValue3() );
    if ( values.end() != std::find( values.begin(), values.end(), value ) )
        return 1;

    // third option I'd use instead
    //

    return 0;
}
like image 883
Mykola Golubyev Avatar asked Jan 27 '26 21:01

Mykola Golubyev


2 Answers

If the values you're looking for are Comparable with operator< (like ints, float and std::strings), then it's faster to use an std::set to put the values there and then check set.find(value) == set.end(). This is because the set will store the values with a certain order that allows for faster lookups. Using an hash table will be even faster. However, for less than 50 values or so you might not notice any difference :) So my rule of thumb would be:

  • Less then 5 items: if with multiple ||

  • 5 or more: put in a set or hash table

like image 68
Joao da Silva Avatar answered Jan 29 '26 13:01

Joao da Silva


you can write a set of template functions which will help you through with this, for example:

template <typename T>
bool InSet(const T & item, const T & i1, const T & i2) {
  return item==i1 || item==i2;
}

template <typename T>
bool InSet(const T & item, const T & i1, const T & i2, const T & i3) {
  return item==i1 || item==i2 || item==i3;
}

Note that you can make InSet to work like it took a variable number of arguments by creating multiple templates with different number of arguments.

And then:

int i;
if (InSet(i, 3, 4, 5)) { ... }
string s;
if (InSet(s, "foobar", "zap", "garblex")) { ... }

etc.

like image 42
Antti Huima Avatar answered Jan 29 '26 11:01

Antti Huima



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!