首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

c++

2013-06-26 
求助 c++本帖最后由 domybest2 于 2013-06-05 11:56:38 编辑小弟要将 string szTemp wo我转换为一个i

求助 c++
本帖最后由 domybest2 于 2013-06-05 11:56:38 编辑 小弟要将 string szTemp = "wo我";   转换为一个int 值。
尝试过  int nTemp = (int)(szTemp.c_str());
可以得到一个 int 值,比如是4934723;
但是我要将这个szTemp所为索引KEY值, 当我在一个比如Find函数输入"wo我"时,发现转换后的int值不是4934723,那这个 情况该怎么处理呢。

或者说有什么其他思路吗


总体 意愿就是 你输入一个string值,我将它转换为一个int,然后放入一个地方,然后当我再次输入同样的string 值的时候,可以在那个地方查找是否已经 有这个值了。

可能说的有些 晕,其实我就是想 添加一个 KEY值,这个KEY值是STRING类型,然后 在FIND函数输入一个同样的STRING类型的值的时候,能够找到它。  大大们说下思路就好,费心了。。。
[解决办法]
典型的键值对哦,STL里的map可以实现你的需求,来点写过的例子:


//map && multimap

void TestMapInsert()
{
map<string, int> coll;
coll.insert(map<string, int>::value_type("zhao", 1));//避免隐式转换
coll.insert(pair<string, int>("hao", 2));//隐式转换
coll.insert(pair<const string, int>("zhaohaoyang", 123));//没有隐式转换
coll.insert(make_pair("yang", 3));//函数生成的pair对象key/value均为non-const,所以隐式转换

pair<map<string, int>::iterator, bool> result;
result = coll.insert(map<string, int>::value_type("zhao", 11));
if (result.second)
{
cout<<"之前没有<zhao, X>键值对,现在成功插入"<<endl;

else
{
cout<<"之前已经存在<zhao, X>键值对,现在插入失败"<<endl;
}
}



//输出关联式容器map,multimap
template<class T>
__forceinline void PrintAssociated(const T &coll, string std = "")
{
typename T::const_iterator pos;
if (std == "")
{
cout<<"all elements:"<<endl;
}
cout<<std<<endl;
for (pos = coll.begin(); pos != coll.end(); ++pos)
{
cout<<pos->first<<" "<<pos->second<<endl;
}
}

void TestMap()
{
map<string, string> coll;
//MyLib2::ClassInteralT cit(1);
//coll["zhao"];
//coll["zhao"] = cit;

coll["zhao"] = "haoyang";
coll["li"] = "hongye";
coll["zhang"] = "san";
coll["li"] = "si";

map<string, string>::iterator pos;
pos = find_if(coll.begin(), coll.end(), MyLib2::value_equals<string, string>("si"));;
//remove_if(coll.begin(), coll.end(), MyLib2::value_equals<string, string>("san"));
//remove(_if)是覆盖型动作,map中的key类型有是const的所以,不能把这个全局算法用早map,multimap上
if (pos != coll.end())
{
cout<<pos->first<<"  "<<pos->second<<endl;
}
else
{
cout<<"未找到"<<endl;
}
PrintAssociated(coll);
}

[解决办法]
你的问题就是string的hash值计算
有各种做法
http://guyot.blog.163.com/blog/static/120574021201011374439716/
上面这个是在网上搜到的。

另外hash map 已经属于C++11的一部分
只是名字是std::unordered_map


以为没用过,所以不知道对应的std::hash<string>是否已经有编译器厂商实现的版本.
猜测可用。

hash表的思想很值得了解。

[解决办法]
c_str指针不能作为string的hash_key,因为字符串赋值时会new一个新的,从键盘输入时还会new一个,从文件加载时又会new一个,用str[3]='a'等不增加长度而改变字符串的值后,指针反而不变……

新的C标准中有unordered_map,同时为string等常用类型写好了hash_key,可以直接用。
自己写的话,最常见的方法是:


unsigned int const hash_key_factor = 37;
unsigned int str_hash_key(string const & value)
{
   int result = 0;
   for( string::const_iterator it = value.begin(); it != value.end(); ++ it )
  {
      result = result * hash_key_factor + static_cast<unsigned int>(*it);
  }
  return result;
}


返回结果再与hash表长取余。
37也可以换成其它质数,可以用不同的值做一下测试。

热点排行