繁体   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