c++ - 从 MFC 的列表框中删除特定项目

标签 c++ mfc

CString dance[] = {L"Atb", L"Tiesto", L"Madonna", L"Paul van Dyk", L"Armin van Burren", L"Jennifer Lopez"};

for(int i = 0; i < m_ItemsListBox.GetCount(); ++i)
{
    CString item;
    int length = m_ItemsListBox.GetTextLen(i);
    m_ItemsListBox.GetText(i, item.GetBuffer(length));
    for(int j = 0; j < sizeof(dance)/sizeof(*dance); ++j)
    {
        if(item != dance[j])
        {
            m_ItemsListBox.DeleteString(i);
        }
    }
}

我正在尝试从列表框 (m_ItemsListbox) 中删除不属于 CString 数组的所有元素。但是我的编码方式不起作用,因为如果第一个元素不同,它将删除它而不搜索整个数组。

这似乎不是一项艰巨的任务,但我真的不知道该怎么做。我认为一种方法应该是使用 CList 而不是数组,因为它有一个 find() 方法,但我不喜欢它,因为我必须手动添加所有元素,你们有另一个想法吗?或者 CList 解决方案是唯一的解决方案?

对不起,我是 MFC 初学者。感谢您的宝贵时间。

最佳答案

嗯,我不愿意从列表框中删除内容,而遍历列表框中的项目似乎是在问问题。 老实说,你可以做这样的事情,我只是凑在一起——构建一个包含你想要删除的所有项目索引的列表,并在最后删除它们。

CList<int, int> ListIndexItemsToRemove;

for(int i = 0; i < m_ItemsListBox.GetCount(); ++i)
{
    CString item;
    int length = m_ItemsListBox.GetTextLen(i);
    m_ItemsListBox.GetText(i, item.GetBuffer(length));

    bool isMatchFound = false;
    for(int j = 0; j < sizeof(dance)/sizeof(*dance); ++j)
    {
        if(item == dance[j])
        {
            isMatchFound = true;
        }
    }
    if (!isMatchFound)
         ListIndexItemsToRemove.AddHead(i);
}
for(int i = 0; i < ListIndexItemsToRemove.GetCount(); ++i)
      m_ItemsListBox.DeleteString(ListIndexItemsToRemove.GetAt(ListIndexItemsToRemove.FindIndex(i));

但是 - 清除整个列表并在每次发生变化时重新填充它可能会更好,正如 Martin 所说(如果它不影响任何东西。

关于c++ - 从 MFC 的列表框中删除特定项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6252558/

相关文章:

c++ 模板参数匹配 std::function 与函数指针

c++ - 在 Linux 上以编程方式设置 DNS 名称服务器

c++ - 将 MFC 库复制到项目

c++ - 使用 Makefile 构建共享库

c++ - boolean 值 c++ 的格式化输出

c++ - 为什么 CMFCMenuBar 没有使用快捷键表?

c++ - 检查单选按钮

debugging - OpenGL 抑制基于 MFC 对话框的应用程序中的异常

c++ - C++11 中的 CRTP 调度

windows - 旧的 Visual Studio 2017/MFC 应用程序仍然有一个非常旧的 "look"到 Windows