在第二个向量中查找向量元素

发布于 2024-08-14 17:34:39 字数 43 浏览 2 评论 0原文

给定两个整数向量,如何确定第一个向量中的某些元素是否存在于第二个向量中?

Given two vectors of integers, how to determinate if there's some element from 1st vector is present in 2nd one?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

在你怀里撒娇 2024-08-21 17:34:39

我想这样的事情应该有效:

std::vector<int> v1,v2;
if(std::find_first_of(v2.begin(),v2.end(),v1.begin(),v1.end()) != v2.end())
   std::cout << "found!\n";

I guess something like this should work:

std::vector<int> v1,v2;
if(std::find_first_of(v2.begin(),v2.end(),v1.begin(),v1.end()) != v2.end())
   std::cout << "found!\n";
紧拥背影 2024-08-21 17:34:39

您可以获取两个向量的 set_intersection ,然后检查所得交集是否为空:

std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::set_intersection(v1.begin()
  , v1.end()
  , v2.begin()
  , v2.end()
  , std::back_inserter(v3));
bool containsElements = !v3.empty();

set_intersection 可以在 #include 中找到。

要使 set_intersection 起作用,必须首先对两个向量进行排序。

You could take the set_intersection of both vectors, and then check if the resulting intersection is empty:

std::sort(v1.begin(), v1.end());
std::sort(v2.begin(), v2.end());
std::set_intersection(v1.begin()
  , v1.end()
  , v2.begin()
  , v2.end()
  , std::back_inserter(v3));
bool containsElements = !v3.empty();

set_intersection can be found in #include <algorithm>

For set_intersection to work, both vectors must first be sorted.

浮生面具三千个 2024-08-21 17:34:39

我想是这样的:

bool contains(const std::vector<int>& vec, int val){
    for(std::vector<int>::const_iterator it=vec.begin(); it!=vec.end(); ++it){
        if(*it==val){
            return true;
        }
    }
    return false;
}

bool contains(const std::vector<int>& from, const std::vector<int>& in){
    for(std::vector<int>::const_iterator it=from.begin(); it!=from.end(); ++it){
        if(contains(in, *it)){
            return true;
        }
    }
    return false;
}

// Example
std::vector<int> a;
std::vector<int> b;

a.push_back(2);
a.push_back(1);
b.push_back(0);
b.push_back(1);

bool contains = contains(a, b);

I think something like this:

bool contains(const std::vector<int>& vec, int val){
    for(std::vector<int>::const_iterator it=vec.begin(); it!=vec.end(); ++it){
        if(*it==val){
            return true;
        }
    }
    return false;
}

bool contains(const std::vector<int>& from, const std::vector<int>& in){
    for(std::vector<int>::const_iterator it=from.begin(); it!=from.end(); ++it){
        if(contains(in, *it)){
            return true;
        }
    }
    return false;
}

// Example
std::vector<int> a;
std::vector<int> b;

a.push_back(2);
a.push_back(1);
b.push_back(0);
b.push_back(1);

bool contains = contains(a, b);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文