Question

Any idea how to remove the duplicate entry from CStringList?

Thanks,

Was it helpful?

Solution

void RemoveDuplicates(CStringList &lst)
{
  for (POSITION pos=lst.GetHeadPosition(); pos; )
  {
    const CString &strValue = lst.GetNext(pos);

    // check next hits in the list
    for (POSITION pos2=pos; pos2; )
    {
      // Save current pointer
      POSITION posToDelete = pos2;
      const CString &strValue2 = lst.GetNext(pos2);
      if (strValue==strValue2)
      {
        // remove duplicate
        lst.RemoveAt(posToDelete);

        // There is a chance that we just deleted the follower from the outer loop
        if (posToDelete==pos)
          pos = pos2;
      }
    }
  }
}

OTHER TIPS

Below is a code to remove duplicate values from CStringArray origData, the output will be stored in "csaNew" array:

    CStringArray csaOld, csaNew;
    bool bAdd = false;
    csaOld.Add(L"A");
    csaOld.Add(L"A");
    csaOld.Add(L"B");
    csaOld.Add(L"B");
    csaOld.Add(L"C");
    csaNew.Add(csaOld[0]);
    for (int i = 1; i < csaOld.GetSize(); i++)
    {
        bAdd = true;
        for (int j = 0; j < csaNew.GetSize(); j++)
        {
            if (csaOld[i].Compare(csaNew[j]) == 0)
            {
                bAdd = false;
                break;
            }
        }

        if (bAdd)
            csaNew.Add(csaOld[i]);
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top