Array/List/Vector type which fills intermediate values in C++?

Viewed 95

I read about the vector/list/map types contained in the stardard template library of C++ and I couldn't find one that behaved as such:

myMap::autofillingmap m;
m[0] = 2; // m[] = [2]
m[1] = 3; // m[] = [2, 3]
m[4] = 5; // m[] = [2, 3, 0, 0, 5]
m[10] = 1 // m[] = [2, 3, 0, 0, 5, 0, 0, 0, 0, 0, 1]

Is there any cpp lib that emulates this behavior?

(beforehand observation: Yes, I do know this is not optimal methodology to work data structures out. Thanks)

1 Answers

 I have wrote myMap struct which use a std::vector<int> to store values, myMap I also have tried a basic Insert() method that interpret your example to assign values.

struct myMap {
        vector<int> _data;
        size_t _capacity;
        myMap(size_t capacity);
        const myMap& operator=(const myMap&);
        int operator [] (int index);
        void Insert(int idx, int value);
};

myMap::myMap(size_t capacity) : _capacity(capacity) {
    _data.resize(capacity);
}

const myMap& myMap::operator=(const myMap& rhs){

    _data = rhs._data;;
    return *this;
}

int myMap::operator[](int idx) {
    return _data[idx];
}

void myMap::Insert(int idx, int value) {

    if (idx >= _data.size())     
        _data.resize(idx+1);      

    _data[idx] = value;
}

demo

Related