c++ - 在 C++ 中查找 char* 数组中的 char* 元素

标签 c++ arrays function pointers void

我正在尝试编写在 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;

    }


}

关于c++ - 在 C++ 中查找 char* 数组中的 char* 元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34387181/

相关文章:

c++ - 捕获所有异常和日志信息

python - Numpy:查找两个不同数组中值的索引条件(来自 R)

javascript - 从 Node JS 中的数组获取条目

c - 如何重新启动程序而不保存其值 (C)

c++ - 需要帮助理解 C++ 中的组合和类函数

c++ - 为什么功能不明确?

C++ 将 Uint32 IP 地址转换为文本 x.x.x.x

php - 多维 JavaScript 数组到 PHP 数组

javascript - 覆盖函数类型原型(prototype)

c++ - 将字符串数组传递给函数