如何避免字符串数组中的重复条目

how to avoid duplicate entry in array of string?

本文关键字:何避免 字符串 数组      更新时间:2023-10-16

在我的小项目中,我想做一个小程序,我必须存储无限的唯一字符串,但用户可以多次输入相同的唯一字符串。但在我的数组中,我希望唯一id只保存一次。简单地说,我不想重复的数据在我的数组。我想在c++中这样做,但不知何故我不能得到逻辑?有人能帮我一下吗?

#include <stdio.h>
#include <iostream>
#include <string>
    using namespace std;
    int main(){
        string str[100],ch;
        int i,j,n;
        j=0;n=0;
        //str[0]= "a";
       do {
         getline(cin,ch);
         for (i=0;i <j; i++){
         if (ch=str[i]){
                        cout << "duplicate" ;
                        }
         str[i] =ch;
         j++;
         }
         n++;
           } while (n =100);
        getchar();
    }

我对c++一窍不通,所以请在这里帮助我

如果你想维护一个唯一的strings列表,那么最简单的事情就是使用正确的工具;即,一个set<string>而不是一个string数组。

编辑:

如果您不需要对字符串集合进行排序(如set所做的),并且您可以使用它,那么使用unordered_set而不是set会更合适。set只会在每次添加字符串时进行不必要的排序。

Edit2:

set是一个关联数组,这意味着给定的键只能有一个元素。对于set<string>,键是您插入的string。如果您多次插入相同的键,在set中仍然只有一个它的实例。

下面是一个示例程序来说明这一点。如果你运行这个,你会发现输出只有一个"foo",即使"foo"被插入了3次:

#include <set>
#include <string>
#include <iostream>
#include <algorithm>
#include <iterator>
using namespace std;
int main()
{
    set<string> my_strings;
    my_strings.insert("foo");
    my_strings.insert("foo");
    my_strings.insert("foo");
    copy( my_strings.begin(), my_strings.end(), ostream_iterator<string>(cout, "n"));
}

还没有编译这个,但这样的东西应该工作,这就是说你应该使用set或类似的更c++sh的方式来解决这个问题,如果你想要一个更有效的解决方案,但从它的声音,你似乎需要更多的基本建议。

int main()
{
    const int maxstrings = 100; // never use magic numbers, instead declare them as a constant
    string str[maxstrings],ch;  // should have other variable names that are more descriptive
    int i,n = 0; // didn't see the need for j here, n contains number of unique strings
    do 
    {
      getline(cin,ch);
      // you may want to check what is in ch first, to see if user doesn't want to enter 100 strings           
      bool duplicate = false;
      for (i=0; !duplicate && i<n; ++i) // check among number of stored strings (n)
      {
        if (ch==str[i]) // use two '=' for equality i.e '=='
        {
          cout << "duplicate:" << ch << endl; // show the duplicate, user friendlier
          duplicate = true;
        }
      }
      // did we find a duplicate? no, then add to array
      if ( !duplicate )
      {
        str[n++]=ch;
      }
   } 
   while ( n < maxstrings );
   getchar();
}

应该使用类vector来保存字符串列表。例如,您可以使用set (http://www.cplusplus.com/reference/stl/set/)。

除此之外,如果您需要检查字符串是否已经存在于set<>对象中,那么您需要使用find()方法检查它:http://www.cplusplus.com/reference/stl/set/find/

我想这就是你所需要的。

供参考:这行:if (ch=str[i]){是完全错误的!你不是在比较!当你赋值时,记住要用'=='而不是'='