6

I'm using a struct. Is there some way to iterate through all the items of type "number"?

struct number { int value; string name; };
Jesse Good
  • 50,901
  • 14
  • 124
  • 166
James Wolfe
  • 77
  • 1
  • 1
  • 2
  • 10
    I'm not sure the question. In C++ we have "maps", i.e. `std::map` and `std::unordered_map`. [See here](http://en.cppreference.com/w/cpp/container) for a list of standard data structures. – Jesse Good Jan 30 '16 at 02:17
  • If you want to create a python-like dictionary, then you want to implement a [hashmap](http://stackoverflow.com/questions/327311/how-are-pythons-built-in-dictionaries-implemented). So look into `std::map` and `std::unordered_map` as suggested both in the comments and answers sections. C++ implementation example [here](http://stackoverflow.com/questions/3578083/what-is-the-best-way-to-use-a-hashmap-in-c). – Reti43 Jan 30 '16 at 02:32

3 Answers3

10

In c++ map works like python dictionary, But there is a basic difference in two languages. C++ is typed and python having duck typing. C++ Map is typed and it can't accept any type of (key, value) like python dictionary. A sample code to make it more clear -

  map<int, char> mymap;
  mymap[1] = 'a';
  mymap[4] = 'b';
  cout<<"my map is -"<<mymap[1]<<" "<<mymap[4]<<endl;

You can use tricks to have a map which will accept any type of key, Refer - http://www.cplusplus.com/forum/general/14982/

AlokThakur
  • 3,599
  • 1
  • 19
  • 32
3

As per my understanding you want to access a value and name using number. You can go for array of structure like number n[5]; where n[0],n[1],...n[4] but we have some additional features in c++ to achieve this with the predefined map, set You can find lots of examples for map

Embedded C
  • 1,448
  • 3
  • 16
  • 29
3

You can use std::map (or unordered_map)

     //  Key  Value Types.
std::map<int, std::string> data {{1, "Test"}, {2, "Plop"}, {3, "Kill"}, {4, "Beep"}};

for(auto item: data) {
                 // Key                  Value
    std::cout << item.first << " : " << item.second << "\n";
}

Compile and run:

> g++ -std=c++14 test.cpp
> ./a.out
1 : Test
2 : Plop
3 : Kill
4 : Beep

The difference between std::map and std::unordered_map is for std::map the items are ordered by the Key while in std::unordered_map the values are not ordered (thus they will be printed in a seemingly random order).

Internally they use very different structures but I am sure you are not interested in that level of detail.

Martin York
  • 257,169
  • 86
  • 333
  • 562