关于map::insert的一点小问题。
关于map::insert的一点小问题。
《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);
};
...全文
相关推荐
C++ map用法总结[可运行源码]
插入元素到map中,可以通过多种方法:使用下标操作符[],使用insert函数,或者使用map的成员函数emplace。
mysql text类型不允许有默认值
默认值的处理可能会影响这种存储机制的效率,因此MySQL选择不支持这一点。当你遇到“mysql `TEXT`类型不允许有默认值”的问题时,有几种解决方法可以考虑:1.
nc65前后台数据库操作的用法
同时,nc65也考虑到了安全性问题,提供了防止SQL注入的功能,确保系统的稳定性和安全性。
c++ map详解
使用 insert 函数插入 value_type 数据我们也可以使用 insert 函数插入 value_type 数据,例如:`mapStudent.insert(map<int, string>:
C++中vector可以作为map的键值实例代码
在插入元素时,我们使用std::vector的insert函数将元素插入到map容器中。通过编译和运行该代码,我们可以看到,vector类型可以直接作为map的键值类型使用。


