Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

initialize 1000 map elements

Just as we can initialize vectors as:

  vector<int> var1(2000,1);

Is it possible to initialize map;

  map<int, int>var2;

for 2000 variables...the reason why I want to initialize are two:

  1. In case I access an element in future e.g. map[100]..I want that map[100]=0
  2. The second reason is that I am using a minimum priority queue which for comparison uses the second value of map i.e. the value stored in map[0]...map[100].
  3. I don't want to use vectors as my indices are really skewed and this leads to a lot of wasted space...i.e. my indices are map[0], map[30], map[56],map[100],map[120],map[190], etc.

Is there some way by which I can initialize the map for say 1000 variables...I am also open to using any other data structure.

Also the conventional way of initializing map i.e.

  map<int, int> m = map_list_of (1,2) (3,4) (5,6) (7,8);

The above way does not work in my case...is there some other way out.PLEASE HELP

EDIT: I can not use for loop as:

This way the key remains fixed which I don't want since the distribution of my keys is skewed. In essence applying for loop in this way is the same as that of vector and this I don't want

like image 400
Jannat Arora Avatar asked Feb 11 '26 05:02

Jannat Arora


1 Answers

You can do it using a surrogate instead of an int in your map, like this:

#include <iostream>
#include <map>

using namespace std;

struct surrogate_int {
    int val;
    surrogate_int() : val(1) {}
    surrogate_int& operator=(const int v) { val=v; }
    operator const int() { return val; }
};

int main() {
map<int,surrogate_int> m;
    m[5] = 5;
    m[7] = 7;
    m[9] = 9;
    for (int i = 0 ; i != 10 ; i++) {
        cout << i << ":" << m[i] << endl;
    }
return 0;
}
like image 136
Sergey Kalinichenko Avatar answered Feb 13 '26 19:02

Sergey Kalinichenko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!