Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-04-09 07:49:13

0001 // name=map_void_int ; gcc $name.cc -std=c++11 -lstdc++ -o /tmp/$name && /tmp/$name 
0002 
0003 #include <cassert>
0004 #include <iostream>
0005 #include <vector>
0006 
0007 #include <unordered_map>
0008 #include <cstring>
0009 
0010 /**
0011 This tests a void* index cache for use with Geant4 objects that lack an index
0012 **/
0013 
0014 struct Surf 
0015 {
0016    const char* name ; 
0017    int         index ; 
0018    Surf(const char* name_, int index_) : name(strdup(name_)), index(index_) {}
0019 }; 
0020 
0021 struct Turf 
0022 {
0023    const char* name ; 
0024    int         index ; 
0025    Turf(const char* name_, int index_) : name(strdup(name_)), index(index_) {}
0026 }; 
0027 
0028 
0029 inline std::ostream& operator<<(std::ostream& os, const Surf& s){ os  << "Surf " << s.index << " " << s.name   ; return os; }
0030 inline std::ostream& operator<<(std::ostream& os, const Turf& s){ os  << "Turf " << s.index << " " << s.name   ; return os; }
0031 
0032 struct Cache
0033 {
0034     typedef std::unordered_map<const void*, int>  MVI ; 
0035     MVI  cache ; 
0036 
0037     void add(const void* obj, int index); 
0038     int find(const void* obj) ; 
0039 }; 
0040 
0041 void Cache::add(const void* obj, int index)
0042 {
0043     cache[obj] = index  ; 
0044 }
0045 int Cache::find(const void* obj)
0046 {
0047     MVI::const_iterator e = cache.end();  
0048     MVI::const_iterator i = cache.find( obj );
0049     return i == e ? -1 : i->second ; 
0050 }
0051 
0052 
0053 int main(int argc, char** argv)
0054 {
0055     Surf* r = new Surf("red",   100); 
0056     Surf* g = new Surf("green", 200); 
0057     Surf* b = new Surf("blue",  300); 
0058 
0059     Turf* c = new Turf("cyan",    1000); 
0060     Turf* m = new Turf("magenta", 2000); 
0061     Turf* y = new Turf("yellow",  3000); 
0062     Turf* k = new Turf("black",   4000); 
0063 
0064     std::vector<const void*> oo = {r,g,b,c,m,y,k} ; 
0065 
0066     // hmm after mixing up the types need to have external info on which is which 
0067     for(unsigned i=0 ; i < 3         ; i++) std::cout << *(Surf*)oo[i] << std::endl ; 
0068     for(unsigned i=3 ; i < oo.size() ; i++) std::cout << *(Turf*)oo[i] << std::endl ; 
0069 
0070     Cache cache ; 
0071 
0072     for(unsigned i=0 ; i < oo.size() ; i++)
0073     {
0074         const void* o = oo[i] ; 
0075 
0076         cache.add(o, i); 
0077         int idx = cache.find(o); 
0078         assert( idx == int(i) ); 
0079     }
0080 
0081     const void* anon = (const void*)m ; 
0082     int idx_m = cache.find(anon) ;  
0083     assert( idx_m == 4 ); 
0084 
0085     return 0 ; 
0086 }
0087 
0088 
0089 
0090