C++空和数组索引

use*_*113 0 c++

有可能做这样的事情:

string word = "Hello";
word[3] = null;
if(word[3] == null){/.../}
Run Code Online (Sandbox Code Playgroud)

在C++中,基本上使数组元素为空.例如,如果我想从数组中删除重复的字符,我首先将它们设置为null,然后每次找到包含null的数组索引时将数组移到左侧.

如果这不可能,那么在C++中做这样的事情的好方法是什么?

Ben*_*ley 5

如果要删除相邻的重复字符,可以执行以下操作:

std::string::iterator new_end = std::unique(word.begin(), word.end());
word.erase(new_end, word.end());
Run Code Online (Sandbox Code Playgroud)

如果要标记要删除的任意字符,可以跳过标记并仅提供相应的谓词std::remove_if:

new_end = std::remove_if(word.begin(), word.end(), IsDuplicate);
word.erase(new_end, word.end());
Run Code Online (Sandbox Code Playgroud)

但是,我想不出在这里使用的适当谓词没有表现出未定义的行为.我只想写自己的算法:

template<typename IteratorT>
IteratorT RemoveDuplicates(IteratorT first, IteratorT last)
{
    typedef typename std::iterator_traits<IteratorT>::value_type
            ValueT;
    std::map<ValueT, int> counts;
    for (auto scan=first; scan!=last; ++scan)
    {
        ++counts[*scan];
        if(counts[*scan] == 1)
        {
            *first = std::move(*scan);
            ++first;
        }
    }
    return first;
}
Run Code Online (Sandbox Code Playgroud)

或者,如果您不关心元素的顺序,您可以简单地对其进行排序,然后使用第一个解决方案.