【问题标题】:Removing duplicate string values in 2d array not working删除二维数组中的重复字符串值不起作用
【发布时间】:2017-07-07 19:08:04
【问题描述】:

我知道这个问题之前已经被问过很多次了,但是我是 C 数组的完全初学者,并且希望避免使用指针(如果可能的话)并使其尽可能简单。 我已将用户的输入用于 char 数组,并希望删除程序中所有重复的字符串值

#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;
        int flag=1; 
    scanf("%d", &N);
    if(1<=N<=10^6){
    char a[N][5];
        for(i=0; i<N; i++){
            scanf("%s", &a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for(k=j+1; k<N; k++){
                        memcpy(a[k], a[k+1], 5);
                    }
                    N--;
                }else{
                    j++;
                }
            }   
        }
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }   
    }
    return 0;
}

输入 3 和 {"abc", "abc", "as"} 只返回值 {"abc"}。 我想将数组设为 {"abc", "as"}。我不明白代码或逻辑的哪里出错了。

更新

我更改了下面提到的代码,但是对于更大的示例,它正在连接字符串

#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;

    scanf("%d", &N);
    if(1 <= N && N <= 1000000){
    char a[N][5];
        for(i=0; i<N; i++){
            scanf("%5s", a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for(k=j+1; k<N; k++){
                        strcpy(a[k-1], a[k]);
                    }
                    N--;
                }else{
                    j++;
                }
            }
        }
        printf("%d\n", N);
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }
    }
    return 0;
}

【问题讨论】:

  • 这个问题是针对 C 还是 C++ 的?它们不是同一种语言。请选择一个并删除另一个标签。
  • 您最里面的循环正在访问a[k+1] 处的数组越界。可能会有更多错误,但这已经是未定义的行为。
  • 顺便说一句,这实际上是 C 代码(C++ 有 std::stringstd::vector 等等,你应该在 C++ 中使用它们)。最好摆脱iostream(您不使用它)并将其作为C问题提出。 -- 哦,对这样的代码使用 C 编译器,而不是 C++ 编译器。
  • 下一个错误:如果您的数组成员只有 5 个字节,为什么还要复制 6 个字节? (你可以只使用strcpy() btw)——然后,scanf("%s", ...)总是是缓冲区溢出,不要使用它。如果您输入更多字符,它不会神奇地停止解析。
  • @FelixPalmen 我已经对缓冲区溢出进行了更改。但是输出仍然保持不变。我应该如何解决数组 out of bounds at a[k+1] 的问题?

标签: c arrays


【解决方案1】:

这是对 cme​​ts 中所有错误的描述:

#include<string.h>
#include<stdio.h>

int main(){
    int N, i, j, k;

    // check the return value!
    if (scanf("%d", &N) != 1) return 1;

    // if(1<=N<=10^6){
    // this is completely wrong:
    // 1. ^ doesn't mean "power" but bitwise exclusive or
    // 2. 1<=N evaluates to 0 (false) or 1 (true), this is ALWAYS <= 10
    // 3. so you have finally 1^6 = 7 -- ALWAYS true as a boolean
    //
    // what you want is:
    if(1 <= N && N <= 1000000){

        char a[N][5];
        for(i=0; i<N; i++){
            // scanf("%s", &a[i]);
            // at least limit the number of characters read (one less
            // than your buffer size because there's a 0 byte added)
            // then, taking a *pointer* of an array is wrong, the array
            // already decays as a pointer, so leave out the `&`
            scanf("%4s", a[i]);
        }
        for(i=0; i<N; i++){
            for(j=i+1;j<N;){
                if(strcmp(a[i],a[j])==0){
                    for (k=j+1; k<N; k++){
                        // memcpy(a[k], a[k+1], 6);
                        // two errors here:
                        // 1. You only have 5 bytes per element, so copy only 5
                        // 2. this is *off by one* for the array index
                        // correct version:
                        memcpy(a[k-1], a[k], 5);
                        // (or use strcpy())
                    }
                    N--;
                }else{
                    j++;
                }
            }   
        }
        for(i=0; i<N; i++){
            printf("%s\n", a[i]);
        }   
    }
    return 0;
}

一般来说,总是启用编译器警告。您的编译器会为您发现大部分这些错误,看看当您在启用 gcc 和警告的情况下编译原始代码时会发生什么:

$ gcc -std=c11 -Wall -Wextra -pedantic -o2darr 2darr.c
2darr.c: In function 'main':
2darr.c:8:12: warning: comparison of constant '10' with boolean expression is always true [-Wbool-compare]
     if(1<=N<=10^6){
            ^~
2darr.c:8:9: warning: comparisons like 'X<=Y<=Z' do not have their mathematical meaning [-Wparentheses]
     if(1<=N<=10^6){
        ~^~~
2darr.c:8:12: warning: suggest parentheses around comparison in operand of '^' [-Wparentheses]
     if(1<=N<=10^6){
        ~~~~^~~~
2darr.c:11:21: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[5]' [-Wformat=]
             scanf("%s", &a[i]);
                     ^
2darr.c:11:21: warning: format '%s' expects argument of type 'char *', but argument 2 has type 'char (*)[5]' [-Wformat=]
2darr.c:6:13: warning: unused variable 'flag' [-Wunused-variable]
         int flag=1;
             ^~~~

【讨论】:

  • 1.) 从main() 返回非零表示错误,1 很常见,操作系统将其作为退出状态返回(例如,脚本可以检查该状态)2.) @ 987654326@ 本身就是一个数组(维度为 5),因为a 是一个二维数组。当您将数组传递给函数时,它会衰减 作为指针(数组无法传递)。你会在这个话题上找到很多,e.g. here
  • 以上更新中给出的较大数据样本会出现更多问题
  • @rut_0_1 不,您没有正确阅读:“至少限制读取的字符数(比缓冲区大小少一个,因为添加了 0 字节)” .您编辑的代码允许 scanf() 写入 5 个字节加上 0 字节,这对于您的数组来说太大了。
  • 当我将它设置为 %4s 时,它会导致程序在输入 5 个字符后退出。我想要N
【解决方案2】:

我的第一反应是使用标准算法用 c++ 编写它。

#include<iostream>
#include<string>
#include<algorithm>
#include<cmath>
#include<vector>
#include<unordered_set>
#include<algorithm>

template<class T, class A>
auto deduplictate_keep_order(std::vector<T, A> &vec) -> std::vector<T, A> &
{
    std::unordered_set<T> seen;
    seen.reserve(vec.size());

    auto check_seen = [&seen](T const &val) {
        return !seen.insert(val).second;
    };

    vec.erase(std::remove_if(vec.begin(), vec.end(), check_seen), vec.end());
    return vec;
};

template<class T, class A>
auto deduplictate_any_order(std::vector<T, A> &vec) -> std::vector<T, A> &
{
    std::sort(vec.begin(), vec.end());
    vec.erase(std::unique(vec.begin(), vec.end()), vec.end());
    return vec;
};


int main() {
    int N, i, j, k;
    int flag = 1;
    std::cin >> N;

    int limit = std::pow(10, 6);
    if (1 <= N && N <= limit) {  //  1 <= N <= will not do what you want. 10^6 is 10 XOR 6. You don't want that.
        std::vector<std::string> a;
        for (i = 0; i < N; i++) {
            a.emplace_back();
            std::cin >> a.back();
        }

        // remove duplicates
        deduplictate_keep_order(a);

        // or this
//        deduplictate_any_order(a);

        for (std::string const &s : a)
            std::cout << s << '\n';
    }
    return 0;
}

【讨论】:

  • 最好的演示为什么有关“C/C++”的问题通常没有意义:)
猜你喜欢
  • 2019-12-17
  • 2022-09-29
  • 2013-05-08
  • 2011-07-19
  • 2017-11-06
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 2016-08-10
相关资源
最近更新 更多