如何比较两个数组?

时间:2015-01-26 12:40:41

标签: c++ arrays loops

我有两个阵列,我想比较它们并发现所有差异。数组看起来像:

  • 组名
  • 成员
  • 用户
  • 用户
  • 用户

等等...

当循环找到“成员”时,它应该将前一个元素作为组名称(因为很少有组是其他组的成员)。

我的实际代码:

for(auto a = 0; a < 100; a++)
{
    const auto data1 = TabList1[a];

    for(auto b = 0; b < 100; b++)
    {
        const auto data2 = TabList2[b];

        if (data1 == 'Members')
        {
            a = a - 1;
            string = TabList1[a];
            a = a + 1;
        }
        if (data1 != data2)
        {
            println "Not match!";
        }
    }
}

当然它更像是伪代码。任何人都可以告诉这段代码有什么问题?

1 个答案:

答案 0 :(得分:0)

&#34;我有两个阵列,我想比较它们并发现所有差异。&#34;

这应该很简单。这假设您的数组具有相同的大小:

for(auto i = std::mismatch(std::begin(TabList1), std::end(TabList1), std::begin(TabList2);
    i.first != std::end(Tablist1);
    i = std::mismatch(std::next(i.first), std::end(TabList1), std::next(i.second)){
    //i is a pair of iterators.
    //The first iterator points to the element of TabList1 that mismatched
    //The second iterator points to the element of TabList2 that mismatched
    //You should operate on those pointers here.
}

&#34;当循环找到&#34;会员&#34;它应该将前一个元素作为组名称(因为很少有组是其他组的成员)。&#34;

这假设TabList1包含至少1个元素。

for(auto i = std::find(std::next(std::begin(TabList1)),std::end(TabList1), "Members");
    i != std::end(TabList1);
    i = std::find(std::next(i), std::end(TabList1), "Members")){
    if(*std::prev(i) != "GroupName"){
        //std::prev(i) holds an iterator to what should have been a "GroupName"
        //i holds an iterator to "Members"
        //You should operate on these pointers here
    }
}