Oblomov
Oblomov

Reputation: 9635

What is the best way to get values of a map as a vector?

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?

Upvotes: 1

Views: 89

Answers (5)

Santiago Varela
Santiago Varela

Reputation: 2237

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).

Upvotes: 1

Jack Fenech
Jack Fenech

Reputation: 108

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);

Upvotes: 2

user7860670
user7860670

Reputation: 37550

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

Upvotes: 1

Shridhar R Kulkarni
Shridhar R Kulkarni

Reputation: 7063

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.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477040

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.)

Upvotes: 3

Related Questions