在 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/