怎么用insert函数给map容器添加元素?
用的是c++ map的insert方法。
函数定义:
single element (1) 插入单个元素 队尾插入
pair<iterator,bool> insert (const value_type& val);
with hint (2) 插入单个元素 在position的位置插入
iterator insert (iterator position, const value_type& val);
range (3) 插入一串元素 一般用的是另一个map中的,从开始到结束
template <class InputIterator> void insert (InputIterator first, InputIterator last);
示例:
// map::insert (C++98)
#include <iostream>
#include <map>
int main ()
{
std::map<char,int> mymap;
// first insert function version (single parameter):第1种
mymap.insert ( std::pair<char,int>('a',100) );
mymap.insert ( std::pair<char,int>('z',200) );
std::pair<std::map<char,int>::iterator,bool> ret;
ret = mymap.insert ( std::pair<char,int>('z',500) );
if (ret.second==false) {
std::cout << "element 'z' already existed";
std::cout << " with a value of " << ret.first->second << '\n';
}
// second insert function version (with hint position):第2种
std::map<char,int>::iterator it = mymap.begin();
mymap.insert (it, std::pair<char,int>('b',300)); // max efficiency inserting
mymap.insert (it, std::pair<char,int>('c',400)); // no max efficiency inserting
// third insert function version (range insertion):第3种
std::map<char,int> anothermap;
anothermap.insert(mymap.begin(),mymap.find('c'));
// showing contents:
std::cout << "mymap contains:\n";
for (it=mymap.begin(); it!=mymap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
std::cout << "anothermap contains:\n";
for (it=anothermap.begin(); it!=anothermap.end(); ++it)
std::cout << it->first << " => " << it->second << '\n';
return 0;
}
m1.insert(make_pair("lucy",20));改成m1.insert(make_pair(string("lucy"),20));
make_pair是std::pair的helper function,是个函数模板,根据参数确定匹配的pair的元素类型,所以LZ的用法弄出来的元素是pair<char* int>类型的。
insert函数
string& insert ( size_t pos1, const string& str, size_t pos2, size_t n );
Inserts a copy of a substring of str at character position pos1. The substring is the portion of str that begins at the character position pos2 and takes up to n characters (it takes less than n if the end of str is reached before).
string& insert ( size_t pos1, const string& str, size_t pos2, size_t n );
Inserts a copy of a substring of str at character position pos1. The substring is the portion of str that begins at the character position pos2 and takes up to n characters (it takes less than n if the end of str is reached before).