c++空和数组索引

C++ empty and array index

本文关键字:索引 数组 c++      更新时间:2023-10-16

是否可以这样做:

string word = "Hello";
word[3] = null;
if(word[3] == null){/.../}
c++中的

,基本上使数组元素为空。例如,如果我想从数组中删除重复字符,我首先将它们设置为null,然后每次发现包含null的数组索引时,都将数组向左移动。

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

如果您想要删除相邻的重复字符,您可以这样做:

std::string::iterator new_end = std::unique(word.begin(), word.end());
word.erase(new_end, word.end());

如果您想标记任意字符以删除,您可以跳过标记,只向std::remove_if提供适当的谓词:

new_end = std::remove_if(word.begin(), word.end(), IsDuplicate);
word.erase(new_end, word.end());

然而,我想不出一个合适的谓词可以在这里使用,而不显示未定义的行为。我只需要写我自己的算法:

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

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

这是可能的,因为字符串的单个元素是字符数组中的元素,因此可以用指针表示,也就是说,您可以检索元素的地址。因此可以设置word[3] = null。你的if -构造是有效的,但编译器打印一个警告,这是因为NULL只是一个指针常数。其他选项为:if (!word[3])if(word[3] == 0)

但是在任何情况下,您都应该考虑使用STL算法来删除重复项。

我认为你应该看看STL中的算法。
你不是很明确你想要删除什么,但也许这有帮助:

    std::string string_with_dup("AABBCCDD");
    std::string string_without_dup;
    std::cout << string_with_dup << std::endl;
    // with copy
    std::unique_copy(string_with_dup.begin(), string_with_dup.end(), std::back_inserter(string_without_dup));
    std::cout << string_without_dup << std::endl;
    // or inplace
    string_with_dup.erase(std::unique(string_with_dup.begin(), string_with_dup.end()), string_with_dup.end());
    std::cout << string_with_dup << std::endl;

如果要删除所有重复项(不仅仅是相邻的重复项),应该使用擦除-删除习惯用法,如下所示

#include <iostream>
#include <map>
#include <string>
#include <algorithm>
using namespace std;
struct is_repeated {
    is_repeated( map<char,int>& x ) :r(&x) {};
    map<char,int>* r;
    bool operator()( char c ) {
        (*r)[c]++;
        if( (*r)[c] > 1 )
            return true;
        return false;
    }
};
int main (int argc, char**argv)
{
    map<char,int> counter_map;
    string v = "hello hello hello hello hello hello hello";
    cout << v << endl;
    is_repeated counter(counter_map);
    v.erase( remove_if(v.begin(), v.end(), counter ), v.end() );
    cout << v << endl;
}

输出(截至此):

hello hello hello hello hello hello hello
helo