Andrew Truckle
Andrew Truckle

Reputation: 19197

Will it be simpler to convert this code from CStringArray to std::vector<CString>?

Given this code:

void CSelectNamesDlg::ShuffleArray(CString strName, CStringArray *pAryStrNames)
{
    if (pAryStrNames == nullptr)
        return;

    const auto iSize = pAryStrNames->GetSize();
    if (iSize > 1)
    {
        // First, we must locate strName in the array
        auto i = CSelectNamesDlg::LocateText(strName, pAryStrNames);
        if (i != -1)
        {
            const auto iName = i;

            // We must now shuffle the names from the bottom to the top
            const auto iCount = gsl::narrow<int>(iSize) - iName;
            for (i = 0; i < iCount; i++)
            {
                CString strTemp = pAryStrNames->GetAt(iSize-1);
                pAryStrNames->RemoveAt(iSize-1);
                pAryStrNames->InsertAt(0, strTemp);
            }
        }
    }
}

int CSelectNamesDlg::LocateText(CString strText, const CStringArray *pAryStrText)
{
    bool bFound = false;
    int i{};

    if (pAryStrText != nullptr)
    {
        const auto iSize = pAryStrText->GetSize();
        for (i = 0; i < iSize; i++)
        {
            if (pAryStrText->GetAt(i) == strText)
            {
                // Found him!
                bFound = true;
                break;
            }
        }
    }

    if (!bFound)
        i = -1;

    return (int)i;
}

If I convert my CStringArray into a std::vector<CString is it going to be simpler to achieve the same PerformShuffle and LocateText methods?

Should I just stay with CStringArray?

Upvotes: 0

Views: 72

Answers (1)

Vlad Feinstein
Vlad Feinstein

Reputation: 11321

I know of 1 (ONE!) benefit of MFC array over std::vector - they support MFC-style serialization. If you use it - you may be stuck.

However, if you don't - I would use std::vector<CString>. Your LocateText (that is overly verbose) will become obsolete - just use find

Also, your ShuffleArray is very inefficient (remove/insert one item at a time). Using a vector will allow you to do something like Best way to extract a subvector from a vector?

Upvotes: 2

Related Questions