0

My C++11 is too weak to find a solution. I have lot of std::vector<std::pair<const char *, int>> variables in my project and therefore the code to check if an entry does exist repeats:

std::vector<std::pair<const char *, RunningProgramMode>> vProgramMode =
{
    { "server", RunningProgramModeServer },
    { "shell",  RunningProgramModeShell  },
    { "client", RunningProgramModeClient },
};

// the following code repeats for each variable
for ( auto const &it : vProgramMode )
{
    if ( !strcmp(sParameter, it.first) )
    {
        programParameters->requestedProgramMode = it.second;
    }
}

Of course I can write a function [which receives std::vector<std::pair<..>> as parameter] which iterates through the vector but I think it would be more elegant when I can extend the std::vector template with my find_member() function which checks with !strcmp(sParameter, it.first) if the vector has the requested entry and returns then .second value.

Something like this:

std::my_vector<std::pair<const char *, RunningProgramMode>> vProgramMode =
{
    { "server", RunningProgramModeServer },
    { "shell",  RunningProgramModeShell  },
    { "client", RunningProgramModeClient },
};
result = vProgramMode.find_member("shell");

For the moment there is no need to check if the value does exist. I want to keep the example simple and focus on the problem.

Peter VARGA
  • 4,780
  • 3
  • 39
  • 75
  • No, you can't add a member function to standard types. – cpplearner May 09 '15 at 16:38
  • 1
    `find_member(vProgramMode, "shell")` is exactly the same number of characters, and has the added benefit that it's actually possible (and straightforward) to implement and doesn't involve wishful thinking. In any case, you might be happier with `std::map` for your data structure. – Igor Tandetnik May 09 '15 at 17:07

1 Answers1

0

My solution:

template<typename T>
class MyVectorForPair
{
private:
    std::vector<std::pair<const char *, T>> classObject;
public:
    MyVectorForPair(std::vector<std::pair<const char *, T>> initVector)
                   { classObject = initVector; }
    auto find_member(const char * sMember, T defaultReturn) -> T;
};

template<typename T>
auto  MyVectorForPair<T>::find_member(const char * sMember, T defaultReturn) -> T
{
    for ( auto const &it : classObject )
    {
        if ( !strcmp(sMember, it.first) )
        {
            return it.second;
        }
    }
    return defaultReturn;
}

I can use it then like this - now it is general:

MyVectorForPair<RunningProgramMode> vProgramMode
(
    {
        { "server", RunningProgramModeServer },
        { "shell",  RunningProgramModeShell  },
        { "client", RunningProgramModeClient },
    }
);

RunningProgramMode result;
result = vProgramMode.find_member(sParameter, RunningProgramModeNotSelected));
Peter VARGA
  • 4,780
  • 3
  • 39
  • 75