【问题标题】:I am trying to return true if the two arrays have common values and return False otherwise如果两个数组具有共同值,我试图返回 true,否则返回 False
【发布时间】:2022-01-17 02:22:07
【问题描述】:

如果两个数组有共同的值,我会尝试返回 true,否则返回 False。 问题是在运行此代码时,我发现数组没有像声明的那样。两个数组之一包含两个数组的值

代码如下:

#include<bits/stdc++.h>
using namespace std;

bool commonValues(char arr1[], char arr2[]){

    for (int i = 0; i < strlen(arr1); i++){
        for(int j = 0; j < strlen(arr2); j++){
            if (arr1[i] == arr2[j]){
                return true;
            }
        }

    }
    return false;

}

int main(){
    char arr1[] = {'a', 'b', 'c', 'd', 'z', 'x', 'k', 'l'};
    char arr2[] = {'e', 'f', 'g', 'h'};
    for (int i = 0; i < strlen(arr2); i++){
    }

    cout<<commonValues(arr1, arr2)<<endl;

    return 0;
}

【问题讨论】:

  • for (int i = 0; i &lt; strlen(arr1); i++){for(int j = 0; j &lt; strlen(arr2); j++){ -- 题外话,但这是实现目标的最天真的方式。想象一下,如果字符串有数千个元素——那将是多少次循环迭代?第二个问题是您在每次迭代时都调用strlen
  • 您应该为数组添加空终止符,例如char arr1[] = {'a', 'b', 'c', 'd', 'z', 'x', 'k', 'l', '\0'};, char arr2[] = {'e', 'f', 'g', 'h', '\0'};.
  • strlen 仅适用于 NUL 终止的 const char* 数组。使用std::size
  • @PaulMcKenzie 我知道这一点。实际上我现在正在学习数据结构和算法课程。我试图编写问题的蛮力解决方案。另外,我不认为 strlen() 每次迭代都会被调用,你知道吗?
  • @MuhammadElmallah -- #include&lt;bits/stdc++.h&gt; -- 去掉这个并使用正确的标题,&lt;iostream&gt;&lt;cstring&gt;。你还声称你正在上课——没有 C++ 老师或班级应该给你这个标题。如果他们这样做了,那么您就没有正确地学习 C++。您收到的dsize 错误可能与使用此标头有关。

标签: c++ arrays


【解决方案1】:

这是一个适合您的现代 C++ 变体:

#include <iostream>
#include <string_view>
#include <unordered_set>

using namespace std::string_view_literals;

bool commonValues(std::string_view a, std::string_view b) {
    std::unordered_set<char> chars_in_a;
    for (auto c : a) {
        chars_in_a.insert(c);
    }
    
    for (auto c : b) {
        if (chars_in_a.contains(c)) {
            return true;
        }
    }
    return false;
}

int main() {
    constexpr auto str_a = "abcdzxkl"sv;
    constexpr auto str_b = "efgh"sv;
    constexpr auto str_c = "jptxo"sv;

    std::cout << str_a << " contains at least one character of " << str_b << ": ";
    std::cout << std::boolalpha << commonValues(str_a, str_b) << std::endl;

    std::cout << str_a << " contains at least one character of " << str_c << ": ";
    std::cout << std::boolalpha << commonValues(str_a, str_c) << std::endl;
}

优点:

  • 使用字符串/字符串视图而不是数组和指针。除非需要(例如,在执行一些非常低级别的操作时),否则避免在 C++ 中使用指针和原始数组。 std::string 通常是要走的路,如果您只是检查一个字符串(例如在您的函数 commonValues 中),您通常希望传递一个 string_view 以提高效率。在您的情况下,字符串永远不会改变,因此您甚至可以使用 constexpr string_view 进行初始化。
  • 以 O(n) 而不是 O(n*m) 运行(其中 n 是较长的字符串长度)。不是在两个数组上都有一个嵌套循环,我们只是将我们到目前为止“看到”的内容存储到一个(无序)集合中,然后我们可以简单地在 O(1)(平均)中查询第二个字符串的元素是否包含在第一个中。我们在这里牺牲了 O(n) 的内存,但在此类算法中,您通常会更快地遇到运行时障碍。

如果需要进一步说明,请添加评论。

【讨论】:

    【解决方案2】:

    一种方法是使用模板非类型参数,如下所示:

    Version 1: 使用模板

    #include<iostream>
    
    //arr1 and arr2 are reference to array of size M and N respectively
    template<std::size_t M, std::size_t N>
    bool commonValues(char (&arr1)[M], char (&arr2)[N]){
    
        for (int i = 0; i < M; i++){//M USED HERE
            for(int j = 0; j < N; j++){//N USED HERE
                if (arr1[i] == arr2[j]){
                    std::cout<<"common element found: "<<arr1[i]<<std::endl;
                    return true;
                }
            }
        }
        return false;
    
    }
    
    int main(){
        char arr1[] = {'a', 'b', 'c', 'd', 'z', 'x', 'k', 'l'};
        char arr2[] = {'e', 'f', 'g', 'h'};
    
        std::cout<<commonValues(arr1, arr2)<<std::endl;
    
        return 0;
    }
    

    另一种方法是将数组的大小传递给函数,如下所示。

    Version 2: 将数组的大小作为参数传递

    #include<iostream>
    #include <string> //needed for std::size with C++17
    //the 2nd and the 4th parameters are the size of the arrays
    bool commonValues(char *arr1, std::size_t M, char *arr2, std::size_t N){
    
        for (int i = 0; i < M; i++){//M USED HERE
            for(int j = 0; j < N; j++){//N USED HERE
                if (arr1[i] == arr2[j]){
                    std::cout<<"common element found: "<<arr1[i]<<std::endl;
                    return true;
                }
            }
        }
        return false;
    
    }
    
    int main(){
        char arr1[] = {'a', 'b', 'c', 'd', 'z', 'x', 'k', 'l'};
        char arr2[] = {'e', 'f', 'g', 'h'};
        //note that we are passing 4 arguments this time.
        std::cout<<commonValues(arr1, std::size(arr1), arr2, std::size(arr2))<<std::endl;
    
        return 0;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-23
      • 1970-01-01
      • 2020-03-04
      相关资源
      最近更新 更多