In c++, is there a way to see if a variable is equal to one of the values? Right now I have to do
if (fExt == "zip" | fExt == "7z" | fExt == "gz" | fExt == "tar")
{
//do something
}
However, is there a more efficient way?
In c++, is there a way to see if a variable is equal to one of the values? Right now I have to do
if (fExt == "zip" | fExt == "7z" | fExt == "gz" | fExt == "tar")
{
//do something
}
However, is there a more efficient way?
Example with a set:
if (std::set<std::string>{"zip", "7z", "gz", "tar"}.count(fExt)) {
std::cerr << "yes" << std::endl;
}
Note that std::set::count()
returns 0 or 1 and provides effectively the same functionality as std::set::contains()
which unfortunately is only introduced in C++20.
This is not too bad as it may skip a few comparisons. It will still not be more efficient, given the extra work to setup and teardown the set. But if your code is called more often, it gets better by re-using the set:
static const std::set<std::string> extensions{"zip", "7z", "gz", "tar"};
if (extensions.count(fExt)) {
std::cerr << "yes" << std::endl;
}
Debatable whether it will be more efficient then doing the four string comparisons but it will probably also not be worse; and it might be easier to maintain.
You could also use an unordered_set
, but for a low number of elements like in your case, it will do more unnecessary computation.
If you can use c++17, I would suggest a fold-expression:
template<typename T, typename ...Opts>
bool any_of(T val, Opts ...opts)
{
return (... || (val == opts));
}
which you can then use like this:
if (any_of(fExt, "zip", "7z", "gz", "tar"))
{
// ...
}
You should put this function into your own namespace to avoid any possible confusion with std::any_of
from the <algorithm>
header.