Initialise vector size within a map

Viewed 495

In my header file, I have a map field:

std::map<std::string, std::vector<double>> priceSMA;

I know the length of the vector, which is 50. How do I go about setting the size of this vector?

If the field was a vector on it's own, It's simple to set the size. But since it's nested within a map I'm lost.

The below throws a syntax error for the vector length:

priceSMA = std::map<std::string, std::vector<double>(50)>();

Any help is appreciated

EDIT

For further clarification, the prceSMA key will be populated with a currency identifier, e.g. "USD". The vector is to store the last 50 values of this currency, where each value has a certain timestamp. Once the first 50 values are populated, when we jump to the next timestamp all the current values in the vector shift over by one value, and populate the last (50th) item in the vector with the new value from the current timestamp.

Prior to the shift, I calculate the average of the 50 values in the vector and store this somewhere else.

The idea is to get a simple moving average over a certain time period.

3 Answers

If you are sure that the size will stay 50, you can use std::map<std::string,std::array<double,50>>.

Otherwise, if you use a vector, each time you add an element to your map, you can initialize the vector with 50 elements equal to 0 with myMap["newKey"] = std::vector<double>(50, 0);

This:

priceSMA = std::map<std::string, std::vector<double>(50)>();

is not correct, because the size of a vector is not part of its type, but for the map, the second template parameter is the type of mapped_value. On a related note, you don't need to explicitly call the default construtor. The map is already default constructed:

std::map< key_type , mapped_value_type> priceSMA; // <- this is a default constructed map

There is not one vector, but each element in the map will have a vector of dynamic size. If you actually want to map strings to arrays of fixed size, take a look at std::array and use something like this:

struct foo {
     std::map<std::string,std::array<double,50>> priceSMA;
     foo() {} // constructor, no need to explicitly call the default constructor
};

Because std::map::operator[] inserts elements when none is present for the provided key, you can then directly access element of the contained arrays like this:

int main(){
    foo f;
    f.priceSMA["blubb"][13] = 42;
}
     map<ll, vector<int>> mp;

    for (int i = 1; i <= n; i++)
    {
        mp[i] = vector<int>(26);
    }

This worked for me !!

Related