65,186
社区成员




《C++ Primer》中文第四版书上P313描述:
m.insert(e)
e是一个用在m上的value_type类型的值。如果键(e.first)不在m中,则插入一个值为e.second的新元素;如果该键在m中已存在,则保持m不变。
该函数返回一个pair类型的对象,包含指向键为e.first的元素的map迭代器,以及一个bool类型的对象,表示是否插入了该元素。
问题:这里所说的是指返回是bool型吗?
如果返回的只是void型,如果有插入失败的情况怎么办?
在编程时,我写了一个程序(如下),然后,当我用if(//放进insert函数)时,程序出错,于是,想知道,是我的程序出问题了,还是这段文字我还没有理解透?
// 以下是程序的部分内容
bool user::inserthelp(string stemp, int itemp)
{
users.insert(type_map_si::value_type(stemp, itemp))
return true;
}
/**
当我用了下面的方法时,提示
1>user.cpp(20): error C2451: “std::pair<_Ty1,_Ty2>”类型的条件表达式是非法的
1> with
1> [
1> _Ty1=std::_Tree_iterator<std::_Tree_val<std::_Tmap_traits<std::string,int,std::less<std::string>,std::allocator<std::pair<const std::string,int>>,false>>>,
1> _Ty2=bool
1> ]
bool user::inserthelp(string stemp, int itemp)
{
if(users.insert(type_map_si::value_type(stemp, itemp)));
return true;
else
return false;
}
**/
#include <iostream>
#include <string>
#include <utility>
#include <map>
using std::string;
class user
{
private:
typedef std::map<string,int> type_map_si;
type_map_si users;
bool inserthelp(string, int);
};
if(users.insert(type_map_si::value_type(stemp, itemp)).second)
bool user::inserthelp(string stemp, int itemp)
{
users.insert(type_map_si::value_type(stemp, itemp));
return true;
}