-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); }无法编译,为什么???

谢谢。

===仅供参考===

创建一个类:

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

然后将 driveMap 声明为

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

然后一切正常。

深入了解 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,减号运算符仅由随机访问运算符支持。

4

1 回答 1

3

std::sort 需要随机访问迭代器,但 std::map 迭代器是双向迭代器。

我认为您应该阅读有关 std::map 的更多信息。它是根据键类型和可选谓词隐式排序的。

于 2012-06-29T03:57:29.983 回答