c++ - 如何避免在字符串数组中重复输入?

标签 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++ 菜鸟,所以请帮帮我

最佳答案

如果你想维护一个唯一的列表 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/

相关文章:

javascript - 更改其属性后渲染数组项

c - 初始化一个未知数量和未知长度的字符串数组

javascript - 返回作为字符串参数传递的值时使用 eval() 的正确方法

.net - ATL COM Server - 从此服务器创建 ATL Server 中定义的 COM 对象

c++ - 使 C++ 代码易于测试的模式

c++ - 执行赋值的赋值左值无效

javascript - 多维数组引用问题

arrays - Scala BigInt 数组

c++ - 析构查询

使用 bool 和 const char 的 C++ 函数重载会产生歧义而不发出警告 (MSVC2012)