如何避免字符串数组中的重复输入?

时间:2011-11-03 19:28:59

标签: c++ arrays string duplicates

在我的小项目中,我想制作一个小程序,我必须存储无限制的唯一字符串,但用户可以多次输入相同的唯一字符串。但是在我的数组中,我只希望只保存一次唯一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 ++的菜鸟,所以请在这里帮助我

3 个答案:

答案 0 :(得分:7)

如果要维护唯一strings的列表,那么最简单的方法就是使用正确的工具来完成工作;即set<string>而不是string的数组。

编辑:

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

EDIT2:

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

这是一个示例程序,用于说明这一点。如果你运行它,你会发现输出只是一个“foo”,即使“foo”被插入了3次:

set

答案 1 :(得分:2)

还没有编译过这个,但是这样的东西应该可以工作,说如果你想要一个更有效的解决方案但是从它的声音中你应该使用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();

}

答案 2 :(得分:0)

您应该使用类似矢量来保留字符串列表。例如,您可以使用一组(http://www.cplusplus.com/reference/stl/set/)。

除此之外,如果你需要检查字符串是否已经存在于集合&lt;&gt;对象,然后你需要使用find()方法检查它:http://www.cplusplus.com/reference/stl/set/find/

我认为这就是你所需要的。

仅供参考:行:if(ch = str [i]){完全错误!你不是在比较!你要分配,记得使用'=='而不是'='。