2015-12-20 313 views
0

我正在嘗試編寫函數,它在char*數組中搜索char *元素,並且函數start檢查此元素,如果元素存在於數組中,我將「找到「,如果不是,則應該」插入「並將元素添加到數組中。在C++中查找char *數組中的char *元素

我寫了這段代碼,但我不知道如何去嘗試它,程序總是給我例外,我能做些什麼來檢查指針數組中的元素?

void checkFunction(char*myArray[], char *element,bool flag) 
{ 
    for (int i = 0; i < strlen(*myArray) ; ++i) 
    { 
     if (myArray[i] == element) 
     { 
      flag = true; 
     } 
    } 
    *myArray = element; 
    flag = false; 

    if (flag) 
    { 
     cout << "Found" << endl; 
    } 
    else 
    { 
     cout << "Inserted" << endl; 
    } 
} 
+7

你是不是準備好使用poiners和數組,這是專家們先進的低層次的語言特點。請使用'std :: string'和'std :: vector'。 –

+0

當您將字符指針與另一個字符指針進行比較時,您並未比較它們的值。你正在比較他們在記憶中的位置。你必須像這樣檢查它們:strcmp(a,b)== 0; – Paulo

回答

2

C++路

#include <iostream> 
#include <vector> 
#include <algorithm> 

using namespace std; 

int main(int argc, const char * argv[]) { 

    vector<string> myStrings { "One", "Two", "Three" }; 

    // std::find() finds the first element that matches a value 
    auto it = find(begin(myStrings), end(myStrings), "Twooo"); 
    if (it != end(myStrings)) { 
     cout << "We found this string; do something..." << endl; 

    } 


} 
0

關於你的函數幾句話:

1.爲什麼你需要的,而不是讓它爲局部變量的第三個參數bool flag,?

2.如果要擴展一個數組,你應該老複製到新分配,然後添加新的元素,你不能只是做:*myArray = element;

3,如果你想通過數組迭代長度/大小,而不是:

for (int i = 0; i < strlen(*myArray) ; ++i) 

傳遞一個額外的參數給你的函數,它指出了數組中的元素個數。

隨着std::stringstd::vector你可以這樣做:

void check_insert (std::vector<std::string>& v, std::string& c) { 

    for (auto i = 0; i < v.size(); ++i) { 
     if (v[i] == c) { 
      std::cout << "Found!\n"; 
      return; 
     } 
    } 

    v.push_back(c); 
    std::cout << "Inserted!\n"; 
} 
+0

非常好。但我認爲你的'for'循環與'arr_begin','arr_end'是錯誤的。其中的每一個都是指向內存中任何位置的char *的指針,而不是數組元素本身的位置。本身。 'for(auto i = myArray; i!=&myArray [n]; ++ i)' – Keith

+0

@Keith您可能是對的:)剛剛編輯。 – Ziezi

+0

@指向數組的第一個元素的指針,當增加'n'次時,其中'n = array-size'將100%到達最後一個元素,因爲「數組是一個以**連續記憶**「。 – Ziezi