1

I want to store random snapshots of a a 1D array arr using a mapping of 2 points say a,b to utilise in a dynamic program. like say

P1 => (4,5)   = [1,1,0,2,1]
P2 => (10,13) = [5,6,3,4,3]
P3 => (15,23) = [11,13,9,12,14]

so on..... Later I need to add them to array A having also n elements like arr. like say A = [1,1,1,1,1]

so now after P1 i have A as : [2,2,1,3,2] and so on till P ends. I am not sure how to map these points P1,P2 ... with the array arr and then later sum it with array A. I tried using a 3D array to store those points and then the array.But it seems bulky and not utilised in an efficient way. Any help is appreciated.

Hemant
  • 1,961
  • 2
  • 17
  • 27

2 Answers2

2

You can use a

std::map<std::pair<int, int>, std::vector<int>> m;

then you can use it as m[{10, 20}].push_back(42);.

The data in the question for example could be stored with

m[{4, 5}] = {1, 1, 0, 2, 1};
m[{10, 13}] = {5, 6, 3, 4, 3};
m[{15, 23}] = {11, 13, 9, 12, 14};
6502
  • 112,025
  • 15
  • 165
  • 265
0

According to this answer posted by GManNickG https://stackoverflow.com/a/2197015/7943474, un unordered_map will use more memory but in your case it can be much faster since you are not going to add/delete points once you initialize your set of data.

In this case you should consider:

#include <unordered_map>

std::unordered_map<std::pair<int, int>, std::vector<int>> uMap;

and then insert your element as:

std::pair<int, int> point(4, 5);
std::vector<int> arr;
arr.push_back(1);
arr.push_back(1);
and so on..

uMap.insert(point, arr);

To find and element in the uMap, you can use the find() method:

std::unordered_map<std::pair<int, int>, std::vector<int>>::const_iterator it = uMap.find(point);

and then update data with

it->second[0] + A[0];
it->second[1] + A[1];
and so on..

For more reference see http://www.cplusplus.com/reference/unordered_map/unordered_map/

Neb
  • 2,270
  • 1
  • 12
  • 22