C ++:从container1中查找不在container2中的任何元素

时间:2016-06-01 22:11:02

标签: c++ algorithm stl std

我有std::set<int>(s)和std::vector<int>(v)。保证向量是有序/唯一的。我想知道v的所有元素是否都在s中(或者只是停在v的第一个元素而不是s中)。我可以将v转换为set并执行== test,但是有没有其他方法而不更改容器类型?

4 个答案:

答案 0 :(得分:9)

std::includes算法是什么?

这是一个简短的用法示例:

vector<int> v1 { 1, 2, 4, 8 };
vector<int> v2 { 1, 2, 3, 8 };
set<int> s { 0, 1, 2, 4, 8, 16 };
cout << includes(s.begin(), s.end(), v1.begin(), v1.end()) << endl;
cout << includes(s.begin(), s.end(), v2.begin(), v2.end()) << endl;

输出:

1
0

答案 1 :(得分:2)

我认为您正在寻找std::set::countstd::unordered_set::count

if( v.size() > s.size() )
{
    // since v has unique values
    // v is not subset of s
    // if you need to find a first element of v not in s
    // you need to run the loop below anyway
}
for( auto i : v )
{
    if( !s.count( i ))
    {
        // i not in s
    }
}

如果您需要v中的所有元素,请使用std::set_difference

答案 2 :(得分:1)

std::set<int>将被订购。如果保证std::vector<int>被排序并包含唯一值,您可以迭代它们并比较项目的值。

std::set<int> s = {...};
std::vector<int> v = {...};

// Default answer. If v.size() > s.size(), the answer is
// definitely false. Otherwise, assume the answer to be true.
bool ans = ( v.size() <= s.size() );

auto si = s.begin();
auto vi = v.begin();

// We need to check for si != s.end()
for ( ; ans == true && vi != v.end() && si != s.end(); ++si )
{
    if ( *si == *vi ) ++vi;
    else if ( *si > *vi ) ans = false;
}
if ( vi != v.end() ) ans = false;
// ...
return ans;

答案 3 :(得分:0)

O(n)解决方案:

#include <iostream>
#include <set>
#include <vector>

bool incCase(std::set<int> &s, std::vector<int> &v)
{
    if( v.size() > s.size())
        return false;

    auto si = s.begin();

    for(int& vv : v)
    {
        for(;;si++)
        {
            if(si==s.end() || *si>vv)
                return false;
            if(*si==vv)
            {
                si++;
                break;
            }
        }
    }

    return true;
}

int main()
{
    std::set<int> s { 0, 1, 2, 4, 8, 16 };
    std::vector< std::vector<int> > vv { 
        { 0, 1, 2, 4, 8, 16 },
        { 0, 2 },
        { 4, 16 },
        { 2, 8, },
        { 4},
        { 1, 4, 16 },
        { 0, 2, 8},
        { },
        { -1, 1, 2, 4, 8, 16 },
        { 0, 1, 2, 4, 8, 32 },
        { 0, 2, 3 },
        { 4, 5, 16 },
        { 3, 8, },
        { 5},
        { 1, 5, 16 },
        { 0, 3, 8},
    };

    int i = 1;
    for(auto &v : vv)
    {
        std::cout<< i++ << (incCase(s,v)?" = True":" = False") << std::endl;
    }
}
相关问题