2012-06-29 44 views
-1
BOOL utils::GetLogicDrivesByFreeSpace(LPTSTR pDrives) 
{ 
    TCHAR szBuff[257]; 
    TCHAR chMaxDrive; 
    DWORD dwLogicalDrives; 
    ULARGE_INTEGER freeBytesAvaliable, maxFreeBytesAvaliable; 
    ULARGE_INTEGER totalNumberOfBytes; 
    std::map< ULARGE_INTEGER, TCHAR > driveMap; 

    maxFreeBytesAvaliable.QuadPart = 0; 
    dwLogicalDrives = GetLogicalDrives(); 
    for (int nDrive = 0; nDrive < 32; ++nDrive) { 
     if (dwLogicalDrives && (1 << nDrive)) { 
      _stprintf(szBuff, TEXT("%c:\\"), TEXT('A') + nDrive); 
      //如果是硬盤分區 
      if (GetDriveType(szBuff) == DRIVE_FIXED) { 
       GetDiskFreeSpaceEx(szBuff, 
        &freeBytesAvaliable, &totalNumberOfBytes, NULL); 
       driveMap.insert(std::pair< ULARGE_INTEGER, TCHAR >(freeBytesAvaliable.QuadPart, TEXT('A') + nDrive)); 
      } 
     } 
    } 
    std::sort(driveMap.begin(), driveMap.end(), [](std::pair< ULARGE_INTEGER, TCHAR > n1, std::pair< ULARGE_INTEGER, TCHAR > n2) -> bool { return (n1.first.QuadPart < n2.first.QuadPart); }); 
    int i = 0; 
    for (std::map< ULARGE_INTEGER, TCHAR >::const_iterator iter = driveMap.begin(); iter != driveMap.end(); ++iter, ++i) { 
     pDrives[i] = iter->second; 
    } 
    return true; 
} 

這個lambda表達式[](std::pair< ULARGE_INTEGER, TCHAR > n1, std::pair< ULARGE_INTEGER, TCHAR > n2) -> bool { return (n1.first.QuadPart < n2.first.QuadPart); }無法編譯,爲什麼?我的lambda表達式在做map map comparions時出了什麼問題?

謝謝。

===正如注意===

創建一個類:

struct CompareLargeInteger { 
    bool operator()(ULARGE_INTEGER n1, ULARGE_INTEGER n2) { 
     return (n1.QuadPart > n2.QuadPart); 
    } 
}; 

然後聲明driveMap作爲

std::map< ULARGE_INTEGER, TCHAR, CompareLargeInteger > driveMap; 

那麼一切都OK。

提供一個洞察MS的STL

template<class _RanIt, 
    class _Diff> inline 
    void _Sort(_RanIt _First, _RanIt _Last, _Diff _Ideal) 
    { // order [_First, _Last), using operator< 
    _Diff _Count; 
    for (; _ISORT_MAX < (_Count = _Last - _First) && 0 < _Ideal;) 
     { // divide and conquer by quicksort 
     _STD pair<_RanIt, _RanIt> _Mid = 
      _Unguarded_partition(_First, _Last); 
     _Ideal /= 2, _Ideal += _Ideal/2; // allow 1.5 log2(N) divisions 

     if (_Mid.first - _First < _Last - _Mid.second) 
      { // loop on second half 
      _Sort(_First, _Mid.first, _Ideal); 
      _First = _Mid.second; 
      } 
     else 
      { // loop on first half 
      _Sort(_Mid.second, _Last, _Ideal); 
      _Last = _Mid.first; 
      } 
     } 

    if (_ISORT_MAX < _Count) 
     { // heap sort if too many divisions 
     _STD make_heap(_First, _Last); 
     _STD sort_heap(_First, _Last); 
     } 
    else if (1 < _Count) 
     _Insertion_sort(_First, _Last); // small 
    } 

__Count = __Last - __First,減號來僅通過隨機訪問opeartor支持。

+0

編譯器說什麼? – OmnipotentEntity

+0

編譯器錯誤C2678 binary' - ':沒有操作符定義,它需要類型'std :: _ Tree_iterator <_Mytree>'的左手操作數(或者沒有可接受的轉換) – Jichao

回答

3

std :: sort需要隨機訪問迭代器,但std :: map迭代器是雙向迭代器。

我想你應該閱讀更多關於std :: map。它基於鍵類型和可選謂詞隱式排序。