怎么用insert函数给map容器添加元素?

怎么用insert函数给map容器添加元素?,第1张

用的是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

}

 

VueList是Vue.js的一个列表组件,如果你想在VueList中使用map,可以在列表渲染中使用v-for指令,例如:

1、{{item}}exportdefault{data(){return{items:[1,2,3,4,5]}}}在上面的代码中,我们使用v-for指令遍历了一个名为items的数组,并为每个数组项渲染了一个li元素。请注意,为了避免Vue.js的重复key警告,每个循环的元素都应该有一个唯一的key属性。在上面的代码中,我们使用数组项的索引作为key。


欢迎分享,转载请注明来源:内存溢出

原文地址:https://www.54852.com/bake/7842050.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-04-10
下一篇2023-04-10

发表评论

登录后才能评论

评论列表(0条)

    保存