Advertisement
mantielero

Untitled

Oct 11th, 2022
3,225
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Nim 1.80 KB | None | 0 0
  1. {.passL:"-lstdc++".}
  2. import std/tables  # Equivalent to C++ std::map
  3.  
  4.  
  5. #{.push dynlib:"libstd++.so".}
  6.  
  7. {.push header:"<utility>".}
  8. type
  9.   CppPair*[T,P] {.importcpp:"std::pair"} = object
  10.  
  11. proc makePair*[T,P](a:T; b:P):CppPair[T,P] {.importcpp:"std::make_pair(@)" .}
  12.  
  13. proc first*[T,P](p:CppPair[T,P]):T {.importcpp:"#.first" .}
  14.  
  15. proc second*[T,P](p:CppPair[T,P]):P {.importcpp:"#.second" .}
  16. {.pop.}
  17.  
  18. {.push header:"<map>"}
  19. type
  20.   CppMap*[T,P] {.importcpp:"std::map".} = object
  21.   CppMapIterator* {.importcpp: "std::map<'0,'1>::iterator".} [K,V] = object
  22.  
  23. proc insert*[T,P](self:CppMap[T,P],val:CppPair[T,P]) {.importcpp:"#.insert(@)" .}
  24.  
  25. proc `[]=`*[K,V](self:var CppMap[K,V], key:K, val:V) {.importcpp:"#[#] = #" .}
  26.  
  27.  
  28.  
  29. # Iterators
  30. proc begin*[K,V](x: CppMap[K,V]): CppMapIterator[K,V] {.importcpp: "begin".}
  31. proc `end`*[K,V](x: CppMap[K,V]): CppMapIterator[K,V] {.importcpp: "end".}
  32.  
  33.  
  34. proc `!=`*[K,V](a,b:CppMapIterator[K,V]):bool {.importcpp: "# != #".} # Used for the iterator
  35. {.pop.}
  36.  
  37.  
  38. {.push header:"<iterator>".}
  39. proc first*[K,V](self:CppMapIterator[K,V]):K {.importcpp:"@->first" .}
  40. proc second*[K,V](self:CppMapIterator[K,V]):V {.importcpp:"@->second" .}
  41.  
  42. proc inc*[K,V](self:CppMapIterator[K,V]) {.importcpp: "++#".} #"#.operator++()" .}
  43. {.pop.}
  44.  
  45. iterator pairs*[K,V](self:CppMap[K,V]):tuple[key:K,value:V] =
  46.   var ini:CppMapIterator[K,V] = self.begin()
  47.   var `end`:CppMapIterator[K,V] = self.`end`()
  48.   while (ini != `end` ):
  49.     yield (ini.first, ini.second)
  50.     inc(ini)
  51.  
  52. #================
  53.  
  54. type
  55.   PersonMap = CppMap[string,int]
  56.   Person = CppPair[string,int]
  57.  
  58. var mymap:PersonMap
  59. var tmp1:Person = makePair("jose", 10)
  60. mymap.insert(tmp1)
  61. mymap.insert( makePair("ana", 20) )
  62. mymap.insert( makePair("maria", 30) )
  63. mymap["jose"] = 15
  64.  
  65. for (k,v) in mymap.pairs():
  66.   echo k
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement