1

I need to satisfy an api function that requires a vector:

void api_function(std::vector<int> vec);

For another reason, I keep values in a

std::map<int,int> map;

Now I need to pass the values of this map to the api_function.

Is there a way to do that without too much space and time overhead, i.e. without iterating through all values or creating a new vector?

Oblomov
  • 8,953
  • 22
  • 60
  • 106

5 Answers5

3

No, there isn't. A vector stores its elements contiguously, and the map does not, and so there's no way to create a contiguous arrangement of ints without iterating and copying.

(General algorithms don't operate on containers for that reason, but rather on a more flexible interface like iterators, so that they don't force the user to provide a particular implementation of a range.)

Kerrek SB
  • 464,522
  • 92
  • 875
  • 1,084
  • True: Unfortunately I need to use that api and it isnt abstracted to use iterators. But thanks, anyway. – Oblomov Apr 15 '17 at 14:52
2

You can do this by using a simple range loop on the map and pushing each value into a vector and then passing that to your function.

Like this:

for (const auto& pair : map)
    vector.push_back(pair.second);
Jack Fenech
  • 108
  • 2
  • 7
2

If a function asks for vector you are bound to give it a vector. At most, this will help you Copy map values to vector in STL.

Community
  • 1
  • 1
Shridhar R Kulkarni
  • 6,653
  • 3
  • 37
  • 57
1

As kerrek SB has stated the answer is no. You will need to iterate through your map.

You can do the following to add values to a dynamic vector container. Iterate through the map using std::pair. In this way you're not using a true iterator:

std::vector<int> vec;

for (std::pair<int, int>& e : map) {
   vec.push_back(e.second);
}  

...
...
api_function(vec);  // Invoke function

Finally you can just call your function from your API with your vector.

This will yield a computational time and space complexity of O(n) (with "n" being the number of values you have contained in your map).

Santiago Varela
  • 2,199
  • 16
  • 22
1

You may want to use a map implementation that uses sorted vector internally ('dense map').

user7860670
  • 35,849
  • 4
  • 58
  • 84