2011-12-14 111 views
0

是否有可能这样做:C++空和数组索引

string word = "Hello"; 
word[3] = null; 
if(word[3] == null){/.../} 
在C++

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

如果这是不可能的在C++中做这样的事情的好方法是什么?如果你想标记为删除任意字符,你可以跳过标记,只是提供相应的谓词std::remove_if

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

+0

*相邻*重复的字符?或任何重复的任何东西? – 2011-12-14 16:58:37

+0

基本上...编号 – 2011-12-14 17:02:16

+0

对不起,不够具体,但我只使用字符串作为例子。我想知道如何为包含ints或其他一般对象的数组做些什么。我对任何重复都感兴趣。 – user1066113 2011-12-14 17:09:21

回答

0

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

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

5

如果你想删除相邻的重复的字符,你可以做到这一点

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

但是,我想不出一个合适的谓词在这里使用,不会出现未定义的行为。我只想写我自己的算法:或者,如果你不关心元素的顺序,你可以简单地对它进行排序,然后使用第一种解决方案。

+0

这似乎是一个非常优雅的方法。你能解释它的作用吗? – user1066113 2011-12-14 17:13:10

0

我想你应该看看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; 
0

如果要删除所有重复(不仅是相邻的,你应该这样使用erase-remove idiom这样

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

输出(截至this):

hello hello hello hello hello hello hello 
helo