在我的小项目中,我想制作一个小程序,我必须存储无限数量的唯一字符串,但用户可以多次输入相同的唯一字符串。但是在我的数组中,我只希望唯一的 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
每次添加字符串时只会进行不必要的排序。
编辑2:
A 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"));
}
关于c++ - 如何避免在字符串数组中重复输入?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8000735/