Skip to content

Instantly share code, notes, and snippets.

@octavifs
Last active March 9, 2021 03:04
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save octavifs/5362297 to your computer and use it in GitHub Desktop.
Save octavifs/5362297 to your computer and use it in GitHub Desktop.
Converts C++ std::map to boost::python::dict
// Converts a C++ map to a python dict
template <class K, class V>
boost::python::dict toPythonDict(std::map<K, V> map) {
typename std::map<K, V>::iterator iter;
boost::python::dict dictionary;
for (iter = map.begin(); iter != map.end(); ++iter) {
dictionary[iter->first] = iter->second;
}
return dictionary;
}
@yimyom
Copy link

yimyom commented Dec 1, 2015

I would rather put const std::map<K,V>& map as a parameter, that is a const ref. It won't change the code but can greatly help the compiler to optimize the code.

@projectDaemon
Copy link

i think auto is better than typename std::map<K, V>::iterator iter;

@ajbrunyee
Copy link

ajbrunyee commented May 15, 2017

addressing comment: iterator doesn't work with const argument here. Code works fine in snippet, though I'm passing by ref.

@MoroJr
Copy link

MoroJr commented Dec 2, 2017

@AntonBrunyee, of course it is not working, because you need a const_iterator over iterator.

@okmechak
Copy link

okmechak commented Jun 3, 2020

How to use this function?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment