2011-12-14 48 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