2011-11-03 82 views
1

在我的小项目中,我想制作一个小程序,我必须存储不限数量的唯一字符串,但用户可以多次输入同一个唯一字符串。但在我的数组中,我只想要唯一的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

'的std :: unordered_set ' –

回答

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(); 

} 
+0

Anders K.能否请你编译并检查它,虽然一切似乎都是正确的,但它不在这里工作。 –

7

如果你想保持唯一strings列表,然后做最简单的办法是使用了合适的工具;即set<string>而不是string的阵列。

编辑:

如果你不需要你的字符串进行排序的集合(如set做),你必须提供给你,它会更适合使用unordered_set而非setset只会在每次添加字符串时进行不必要的排序。

EDIT2:

set是关联数组,这意味着只能有一个给定的密钥的一个元素。在set<string>的情况下,密钥是您插入的string。如果多次插入相同的密钥,set中仍然只有一个密钥。

下面是一个示例程序,说明了这一点。如果你运行这个,你会发现在输出仅仅是一个“富”,虽然“富”插入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")); 
} 
+0

我建议'的std :: unordered_set'如果你拥有它,'的std :: set'如果不是。 –

+0

好的建议;编辑。 –

+0

用户会连续输入说出他们的电子邮件地址,但是我想将它作为字符串存储在数组中,因此即使它们输入了两次或更多次它也不会存储在我的数组中,可以设置这样做吗? –

0

你应该使用矢量样保持一个字符串列表。例如,您可以使用一套(http://www.cplusplus.com/reference/stl/set/)。

除此之外,如果你需要检查字符串设定<>对象上已经存在,那么你就需要使用find()方法来检查它:http://www.cplusplus.com/reference/stl/set/find/

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

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