【问题标题】:How to compare an element of array with all the elements of another array如何将数组的元素与另一个数组的所有元素进行比较
【发布时间】:2019-06-13 14:11:26
【问题描述】:

我有 2 个数组:a [ ] = {1,2,3,4,5,6} 和 b [ ] = {1,2,6}。如何将数组 a 中的所有元素与数组 b 中的所有元素进行比较。例如,我将 a 中的第一个元素与 b 中的所有元素进行比较,如果它们不相等,则显示并继续检查。所以毕竟我需要得到 c [ ] = {3,4,5}。

请帮帮我。

for(i=0;i<n;i++)
{
    for(j=0;j<k;j++)
    {
        if(sf[i].r != temp[j].r)
        {
            cout<<sf[i].r<<" ";
        }
    }
}

其中 sf[ ] .r = {1,2,2,2,3,5,6,6,7,8,8} 和 temp[ ].r = { 1,3,5,7} 。输出必须是 {2,2,2,6,6,8,8}。

【问题讨论】:

  • 你很好地描述了算法。是什么阻止了您实施它?
  • 查看std::set_difference
  • @Ferrrnando,顺便说一句,您可能会显示您的代码。
  • @vahancho 检查更新
  • @Ferrrnando,这有点令人困惑。 sf[ ] .r 是指数组还是数组中的元素? r 是什么?

标签: c++ arrays struct codeblocks


【解决方案1】:

只需使用std::vector&lt;int&gt; 来构建您的结果,例如:

std::vector<int> set_difference;
for (int elem_a : a)
{
    if (std::find(std::begin(b), std::end(b), elem_a) == std::end(b))
    {
        set_difference.push_back(elem_a);
    }
}

【讨论】:

  • 当我启动它时,它说开始并且不是 std 的成员。我能做什么?
  • @Ferrrnando #include &lt;iterator&gt; 对于std::find,您还需要#include &lt;algorithm&gt;,对于#include &lt;vector&gt;,对于std::vector,您还需要#include &lt;vector&gt;
【解决方案2】:
int a[] = { 1, 2, 3, 4, 5, 6 };
int b[] = { 1, 3, 6, 2, 5, 9 };
std::vector<int> c;

for (int i = 0; i < sizeof(a); i++)
{
    for(int j = 0; j < sizeof(b); j++)
    {
        if (a[i] == b[j])
            std::cout << a[i] << " equals " << b[j] << std::endl;
        else
        {
            std::cout << a[i] << "not equals " << b[j] << std::endl;
            c.push_back(a[i]);
        }
    }
}

【讨论】:

  • 它比较第一个元素。 from a 和 all from b ,但在那之后,它开始比较第一个 elem。 a 和其他 elem 的 a。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多