【问题标题】:How to remove the duplicate entry from CStringList? [closed]如何从 CStringList 中删除重复的条目? [关闭]
【发布时间】:2013-11-08 15:37:58
【问题描述】:

知道如何从 CStringList 中删除重复条目吗?

谢谢,

【问题讨论】:

  • RemoveAt,与任何其他条目相同。
  • 什么是“重复条目”?到目前为止,您尝试过什么?

标签: visual-c++ stl mfc atl


【解决方案1】:
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;
      }
    }
  }
}

【讨论】:

  • Getting error error C2440: 'initializing' : cannot convert from 'struct __POSITION *' to 'int'
  • 你有一个旧的编译器。在位置更改自动。我会在我的答案中改变它。
【解决方案2】:

下面是从 CStringArray origData 中删除重复值的代码,输出将存储在“csaNew”数组中:

    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]);
    }

【讨论】:

  • 请在您的答案中添加一些解释,以便其他人可以从中学习
  • 添加了一些描述,我认为代码是不言自明的。
  • 这段代码如何检查“重复条目”?你能检查一下你的代码如何处理列表“A”、“B”、“A”吗?
  • 感谢您的留言,我对代码做了一些修复。它工作正常,经过测试。
猜你喜欢
  • 2015-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-12-17
  • 2017-03-30
  • 1970-01-01
  • 2012-08-06
相关资源
最近更新 更多