簡體   English   中英

在C ++中的char *數組中查找char *元素

[英]Find char* element in array of char* in 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;
    }
}

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;

    }


}

關於您的功能的幾點評論:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM