c++ - 在 char 数组中查找不重复的字母。我的程序运行错误。需要帮忙

标签 c++ data-structures

在 char 数组中查找没有重复的字母。我的程序运行错误。需要帮助

#include <iostream>
#include <vector>
#include <list>
# include <ext/hash_map>

/*
find none duplicated letter from char array */

using namespace __gnu_cxx;
using namespace std;

list<char> find_Noneduplicate_idx(const vector<char>& A)
{
hash_map<char,int> X;
list<char> idx;
for ( int i = 0; i < A.size(); ++ i ) 
{
  hash_map<char, int>::iterator it = X.find(A[i]);
  if ( it != X.end() )  
  {
    X[A[i]]++;
  }
  else
  X[A[i]] = 1;
}
for (hash_map<char,int>::iterator iter = X.begin(); iter!=X.end();++iter)
{
    if (iter->second == 1)
        idx.push_back(iter->first);
}

return idx;
}

int main()
{

    int myints[] = {'H','A','C','B','C','H','Z'};
    vector<char> fifth (myints, myints + sizeof(myints) / sizeof(char) );
    list<char> idx = find_Noneduplicate_idx(fifth);
    for (list<char>::iterator iter = idx.begin(); iter != idx.end(); ++iter)
    {
        printf("%c",*iter);
    }
    return 0;

}

输出应该是:A,B,Z 但我的结果不是。

我编辑了它,现在输出是“AB?Z`??”怎么了?

最佳答案

首先,改变这个

int myints[] = {'H','A','C','B','C','H','Z'};

char myints[] = {'H','A','C','B','C','H','Z'};

否则,在下一行创建 vector 时,您将读到该数组的末尾。尝试 std::cout << fifth.size()看看你的 vector 有多大!

或者,或者,更改 sizeof(char)sizeof(myints[0]) -- 在 sizeof 中使用名称而不是类型是一种很好的做法无论如何。

然后添加缺失的else X[A[i]] = 1; 之前的关键字,程序将产生预期的结果。

关于c++ - 在 char 数组中查找不重复的字母。我的程序运行错误。需要帮忙,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5006704/

相关文章:

java - 循环旋转: Issue with rotate left

c++ - 通过 gcc-6 在 OSX Sierra 上安装时,保持 "FATAL:/opt/local/bin/../libexec/as/x86_64/as: I don' t 理解 'm' 标志!”错误

c++ - 如何从 "universal character name"转换为 wchar_t 序列?

c++ - 为加密程序加载二进制数据

data-structures - 表示分段连续范围的数据结构?

c - 在二叉树中插入元素

c++ - 为什么使用 mkdir() 函数比使用系统 ('mkdir path' 快得多)?

c++ - 值如何存储在 char 中

c++ - Stack 的链表实现

java - 创建一个支持 "snapshots"的 ConcurrentHashMap