繁体   English   中英

C ++空和数组索引

[英]C++ empty and array index

是否可以做类似的事情:

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

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

我认为您应该看看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;

这是可能的,因为字符串的单个元素是字符数组中的一个元素,因此可以表示为指针,即可以检索该元素的地址。 因此,您可以设置word[3] = null if -construct有效,但是编译器会显示警告,这是因为NULL只是指针常量。 备选方案是: if (!word[3])if(word[3] == 0)

但是无论如何,您都应该考虑使用STL 算法删除重复项。

如果要删除所有重复项(不仅是相邻的重复项,则应使用“ 删除删除”成语)

#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 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM