如何避免字符串数组中的重复条目
how to avoid duplicate entry in array of string?
在我的小项目中,我想做一个小程序,我必须存储无限的唯一字符串,但用户可以多次输入相同的唯一字符串。但在我的数组中,我希望唯一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]){是完全错误的!你不是在比较!当你赋值时,记住要用'=='而不是'='
- 如何从字符串向量构造对象并避免复制?
- 如何避免将数据缓冲区的额外副本复制到字符串?
- 有没有办法在初始化字符串时避免来自 clang-tidy(fuchsia-default-arguments)的警告?
- C++中的 Json:将数字解析为字符串以避免浮点不准确
- 如何修复我的字符串以避免运行时错误?
- 如何避免字符串到整数转换情况下的无效参数异常
- 如何在C++中避免魔术字符串和魔术数字
- 如何使用 c 字符串并避免溢出 c++
- 避免在 ctor 初始值设定项列表中的字符串赋值中使用双重调用函数
- 避免在字符串中分支 if-else 以类型调度
- 字符 * 和字符串在C++中有何不同?(在描述中编写代码)
- 订购一系列字符串,同时避免重复
- C++ 避免 if 和硬编码字符串
- 如何避免构建新字符串
- std::字符串流,直接输出缓冲区/字符串结果访问,避免复制
- Qt:避免在字符串更改的情况下重建应用程序
- 如何避免C字符串出现许多类似的重载
- 如何避免在转换字符串令牌流时重复istringstream构造
- 如何避免字符串数组中的重复条目
- Spoj one0如何避免字符串