【问题标题】:C++ How to check if contents of vector exist in another vector?C ++如何检查向量的内容是否存在于另一个向量中?
【发布时间】:2018-09-01 15:41:47
【问题描述】:

我正在尝试编写一个程序来检查一个向量的内容是否存在于另一个向量中。例如:

vector<int> a = {1, 2};
vector<int> b = {6, 5, 3, 1, 9, 2};

比较这两个向量时返回 true,因为 a 的内容存在于 b 的某个位置。

vector<int> a = {1, 2}
vector<int> b = {3, 1, 5, 6}

这将返回 false,因为 a 中的 所有内容 都不存在于 b 中。

我已经尝试过使用while 循环,但我不知道如何让循环中断。

bool check_vec(vector<int> a, vector<int> b){

    int checker = 0;

    int i = 0;
    int q = 0;

    while ( true ) {
        if(b.at(i) == a.at(q)) {
            checker++;
            i = 0;
            q++;
            if(checker == a.size())
                return true;

            i++;

        }
    }
}

【问题讨论】:

  • 那甚至无法编译。发布minimal reproducible example
  • 至少,您至少缺少两个右括号
  • 为什么第一个例子会返回true? a 中的 2b 中不存在。在任何情况下,您都应该通过vector&lt;int&gt;&amp; 参考来获取输入向量。如果先对向量进行排序然后检查b 是否以与a 相同的值开头,则搜索可能会更容易。或者使用std::includes()std::set_intersection() 而不是手动搜索

标签: c++ vector int


【解决方案1】:
#include <iostream>
#include <vector>
#include <iterator>
#include <algorithm>

int main() {

    std::vector<int> a = {1, 2};
    std::vector<int> b = {6, 5, 3, 1, 9, 2};

    vector<int> c( a.size() + b.size() );
    std::cout "\nFirst vector values are ...\n";
    std::copy( a.begin(), a.end() std::ostream_iterator<int>( std::cout, "\t" );
    std::cout << '\n';

    std::cout << "\nSecond vector values are ...\n" << endl;
    std::copy( b.begin(), b.end(), std::ostream_iterator<int>( std::cout, "\t" );
    std::cout << '\n';

    auto pos = std::set_difference( a.begin(), a.end(), b.begin(), b.end(), c.begin() );
    c.resize( pos - c.begin() );

    std::cout << "\nValues present in vector one but not in vector two are ...\n";
    std::copy( c.begin(), c.end(), std::ostream_iterator<int>( cout, "\t" ) );
    std::cout << '\n';

    c.clear();
    c.resize( a.size() + b.size() );

    pos = std::set_union( a.begin(), a.end(), b.begin(), b.end(), c.begin() );
    v.resize( pos - c.begin() );

    std::cout << "\nMerged vector values in vector are ...\n";
    std::copy( c.begin(), c.end(), std::ostream_iterator<int>( cout , "\t" ) );
    std::cout << "\n\n";

    std::cout << "\nPress any key and enter to quit.\n";
    std::cin.get();

    return 0;
}      

【讨论】:

    【解决方案2】:

    使用循环遍历第一个向量的内容。第二个向量不需要循环,只需使用std::find

    for (auto a_elt: a) {
        if (std::find(b.begin(), b.end(), a_elt) == b.end()) {
            return false;
        }
    }
    return true;
    

    你也可以使用std::all_of:

    return std::all_of(a.begin(), a.end(), [](int a_elt) {
        return std::find(b.begin(), b.end(), a_elt) != b.end();
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 2017-04-07
      相关资源
      最近更新 更多