Home > OS >  C - Copy keys of one map to other
C - Copy keys of one map to other

Time:07-18

I have something like this -

#include <iostream>
#include <map>

int main() {
  
  std::map<std::string, int> size = {
    {"a", 1},
    {"b", 2},
    {"c", 3}
  };

  std::map<std::string, void*> ptr;
  auto it1 = size.cbegin();
  auto it2 = ptr.cbegin();
  while(it1 != size.cend()) {
    it2->first = it1->first; //error
    it1  ;
    it2  
  }
}

I want to copy just the keys of the map size to map ptr before adding the values in map ptr. How can I do that?

Edit: I tried loops but itgives error

CodePudding user response:

Your problem is that your ptr.cbegin is equal to ptr.cend() because you don't have any element in your ptr map yet. Thus you need to create those elements. Additionally if you want to mutate it1 by incrementing it, then you should use begin() instead of cbegin which returns a const-pointer.

You can also transform the second map into an unordered_map for better performance, since you don't need the elements to be ordered for you:

#include <iostream>
#include <map>
#include <unordered_map>

int main() {
  
  std::map<std::string, int> size = {
    {"a", 1},
    {"b", 2},
    {"c", 3}
  };

  std::unordered_map<std::string, void*> ptr;
  auto it1 = size.begin();
  
  std::cout << (ptr.cbegin() == ptr.cend());

  while(it1 != size.cend()) {
    ptr[it1->first] = nullptr; //error
    it1  ;
  }
}

Note: Consider using a smart pointer for your void* unless you really really need it.

CodePudding user response:

You can iterate over the keys of size with

std::for_each(std::cbegin(size), std::cend(size), [&](const std::pair<std::string, int> &pair) { /* in here, "pair.first" accesses each key */ }

That said, it is never necessary nor wise to declare a variable void * in C . Anything can decay to a void *.

  • Related