std :: find多个元素和逻辑运算符

时间:2016-06-02 12:14:22

标签: c++ algorithm find operators logical-operators

我目前有

if(std::find(row.begin(), row.end(), 12) != row.end()) {
    std::cout << "12 Found"
}

并希望将其扩展为

if(std::find(row.begin(), row.end(), 12 && 13 || 18 && 19)  != row.end()) {
    std::cout << "12 and 13 Found or 18 && 19"
}

我显然可以使用多个if语句执行此操作,但我希望尽可能快地执行此操作。有什么东西可以让我这样做吗?

3 个答案:

答案 0 :(得分:1)

我会说老式的范围迭代效果最好,在这里:

bool found12=false;
bool found13=false;

for (const auto &value:row)
{
   if (value == 12)
        found12=true;

   if (value == 13)
        found13=true;

   if (found12 && found13)
        break;
}

泡沫,冲洗,重复18&amp; 19。

答案 1 :(得分:1)

不是最优雅的,但能完成工作:

std::array<bool, 4> found = {false};
if(std::any_of(v.begin(), v.end(), [&found](int i) 
        {
            if(i == 12) found[0] = true;
            if(i == 13) found[1] = true;
            if(found[0] && found[1]) return true;

            if(i == 18) found[2] = true;
            if(i == 19) found[3] = true;

            if(found[2] && found[3]) return true;
            return false;
        })) 
{
    std::cout << "12 and 13 Found or 18 && 19" << std::endl;
}

答案 2 :(得分:1)

这个答案可能不适合这个问题,但我认为这很有趣,它可以派上用场:

#include <algorithm>
#include <numeric>
#include <iostream>
#include <map>
#include <vector>
#include <utility>

int main()
{
    std::vector<int> row{ 1, 2, 7, 11, 13, 17, 19 };
    std::map<int,bool> m {std::make_pair(12,false), std::make_pair(13,false), std::make_pair(17,false), std::make_pair(18,false) };

    m = std::accumulate(row.begin(), row.end(), m, 
                        [](std::map<int,bool> m, int i) { 
                            auto it = m.find(i); 
                            if (it != m.end()) it->second = true;
                            return m;});

    std::cout << ((m[12] && m[13]) || (m[17] && m[18])) << std::endl;
}

根据输入,它设置根据请求的元素填充的地图。然后可以更容易地在地图上完成逻辑 请注意,由于每个元素都在复制地图,因此这绝不是一个高效的解决方案。

Revolver_Ocelet的改进(更快更干净),取自他在评论中链接到Corilu:

#include <algorithm>
#include <numeric>
#include <iostream>
#include <map>
#include <vector>
#include <utility>
#include <functional>

int main()
{
    using lookup_t = std::map<int,bool>;
    std::vector<int> row{ 1, 2, 7, 12, 13, 17, 19 };
    lookup_t m {std::make_pair(12,false), std::make_pair(13,false), std::make_pair(17,false), std::make_pair(18,false) };

    std::accumulate(row.begin(), row.end(), std::ref(m),
                        [](lookup_t& m, int i) {
                            auto it = m.find(i);
                            if (it != m.end()) it->second = true;
                            return std::ref(m);});

    std::cout << ((m[12] && m[13]) || (m[17] && m[18])) << std::endl;
}
相关问题