Recently, we are working on a SPC/SQC project. One of them uses STL map. I got a little idea and shared it with you.
We know that when we insert a data pair to a map, the elements in the map will be inserted to the corresponding node in a certain order. In other words, the data will be read sequentially from the map header, the data sequence is different from the sequence when you insert data. The example is as follows:
STD: Map <double, int> dnmap;
Dnmap [10.0] = 1;
Dnmap [2.9] = 2;
Dnmap [20.4] = 3;
STD: Map <double, int >:: iterator it = dnmap. Begin ();
For (; it! = Dnmap. End (); ++ it)
{
STD: pair <double, int> _ p = * it;
STD: cout <"Key =" <_ p. First <"value =" <_ p. Second <Endl;
}
The output sequence is:
Key = value =
2.9 2
10.0 1
20.4 3
If the map key is a user-defined type T, you must also implement a comparison operator in T. The specific details are not mentioned here.
But if you think map is suitable for you, but you just want to insert the data in the map to keep the sequence at the time of initial insertion, what should you do?
Let's take a look at the map declaration form in STL (http://www.sgi.com/tech/stl/Map.html)
Map <key, Data, compare, alloc>
Note that the third parameter
Compare: The key comparison function, a strict weak ordering whose argument type isKey_type; It returnsTrueIf its first argument is less than its second argument, andFalseOtherwise. This is also definedMap: key_compare.
The function is to compare the key size and determine the order of map nodes in a certain order. Of course, we can customize this function object to implement the sorting rules we want.
Okay, I have talked a lot about it. My approach is
Template <class T>
Struct disablecompare: public STD: binary_function <t, t, bool>
{
Bool operator () (t lhs, t RHs) const
{
Return true;
}
};
In this way, the custom map is used:
STD: Map <double, Int, disablecompare <double> SMAP;
SMAP [10.9] = 1;
SMAP [3.5] = 2;
SMAP [30.0] = 3;
SMAP [2.4] = 4;
The data insertion sequence can be maintained.