Suggestions for implementing Sparse Vector without using external libraries

I need to use a sparse vector for some things in my current project. But, since I am not responsible for the project, I cannot use any external libraries that I want. I have only STL and OpenCV.

I looked at several answers on stackoverflow, but they either focus on a specific approach , comparing a limited number of approaches (2) and external libraries when they relate specifically to sparse vectors. There are also great ideas for implementing a sparse matrix .

What I want is, in particular, a sparse vector (indexes will always be in 1 dimension, data is not relevant for this issue). I would like something that will not be a project for its implementation, but can be used for more than demonstration purposes (for example, I want to achieve decent speed and not too much memory overhead) is used later. The options I reviewed included:

  • adapting SparseMat 's OpenCV implementation to my needs
  • using std::mapto store values ​​(or perhaps create a very simple wrapper that will return the default value if indexing a null element)
  • using std::vector< std::pair < int , data_type > >where I could store index and data in elementsstd::pair

- / ? , , , . , , , , - , .


:

  • , , ( , 100%, )
  • , ( , ).
  • (), ,
  • 500
  • , ( )

, , .

+5
2

, std::map . SpareseMat, , , , std::map O(log(n)) lookup, O(log(n)) . vector ( O(n)). O(1) , O(n) . , , , , std::map .

vector , map , , ( , , , ).

hash, O(1) , , O(log(n)) - , . , , , , O(log(n)), - std::map.


. , , , , , , :

, . push_back O(1). 1 . 2:

int dot = 0;
unsigned int index_v1 = 0, index_v2 = 0;
while (index_v1 < v1.size() && index_v2 < v2.size())
    if (v1[index_v1].first == v2[index_v2].first)
        dot += v1[index_v1++].second * v2[index_v2++].second;
    else if (v1[index_v1].first < v2[index_v2].first)
        ++index_v1;
    else
        ++index_v2;

, , , , (O(log(n)) ).

, , , . , .

, - , ( ). O(n), , .

1 , O(1) O(log(n)) n ~= 500 .

2 map , . , std::map , node O(1).

+5

, wrap std::map<size_t, YourData> :

template <typename V>
class SparseVector {
public:

private:
    std::map<size_t, V> specificValues;
    V defaultValue;
};

map (find/insert/update), , - , , .

+2

All Articles