开发者

Sort CMap Key by String Length

开发者 https://www.devze.com 2022-12-23 13:28 出处:网络
Previously, I am using STL map to perform the mentioned task. struct ltstr { bool operator()(std::string s1, std::string s2) const

Previously, I am using STL map to perform the mentioned task.

struct ltstr
{
    bool operator()(std::string s1, std::string s2) const
    {
      const int l1 = s1.length();
      const int l2 = s2.length();
      if (l1 == l2) {
          // In alphabetical order.
          return s1.compare(s2) < 0;
      }
      // From longest length to shortest length.
      return l1 > l2;
    }
};
std::map<std::string, int, ltstr> m;

How can I perform the same task using CMap?

// How to make key sorted by string length开发者_开发技巧?
CMap<CString, LPCTSTR, int, int> m;


You cannot. From the MSDN documentation for CMap:

You might think that this iteration is sequential by key value; it is not. The sequence of retrieved elements is indeterminate.


The sequence in a map is determined by the hashing value, and is for all intents and purposes... random.

Instead, you may want to keep/generate a sorted list of pointers to the keys or something like that.

0

精彩评论

暂无评论...
验证码 换一张
取 消