C++如何打印在2数组中重复多少个元素

c++ how print how many element are repeated in 2 array?

本文关键字:数组 多少 元素 何打印 打印 C++      更新时间:2023-10-16

我有两个数组,我想计算两个数组之间有多少元素是相同的。我尝试了很多次,但输出不正确。正确的应该是6次但输出在代码中是 4 次。

注意:如果s1 "ss"并且s2 "ss",则结果2

这是我的代码:

#include <iostream>
#include <string>
using namespace std;
int main() {
    char s1[] = "FOOBART";
    char s2[] = "BFORATO";
    int flag=0;
    for(int i=0, j=0; i < sizeof(s1) && j < sizeof(s2); ) {
        if(s1[i] == s2[j]) {            
            flag++;
            i++;
            j++;
        } else if(s1[i] < s2[j]) {
            i++;
        } else {
            j++; 
        }
    }
    cout << flag;
}

s1 的所有元素都存在于两个字符串中,因此输出将等于 s1 的长度。这是正确的代码

#include <iostream>
using namespace std;
int main() {
    char s1[] = "FOOBART";
    char s2[] = "BFORATO";
    int count=0;
    for (int i=0; i<sizeof(s1)-1; i++) {
        for (int j=0; j<sizeof(s2)-1; j++) {
            if (s1[i]==s2[j]) {
                count++;
                break;
            }
        }
    }
    cout<<count<<endl;
}

希望这对你有帮助

使用 STL 算法的解决方案:

#include <iostream>
#include <algorithm>
#include <string>
int main()
{
    const std::string s1 = "FOOBART";
    std::string s2 = "BFORATO";
    int count = 0;
    auto beg = begin(s2);
    for(auto& elm : s1)
    {
        auto x = find(beg, end(s2), elm);
        if(x != end(s2))
        {
            *x = *beg;//get rid of elment and reduce the range of search.
            ++beg;
            ++count;
        }
    }
    std::cout << count;
    return 0;
}