我正在尝试编写在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;
}
}
发布于 2015-12-20 16:16:03
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;
}
}
发布于 2015-12-20 15:59:04
很少有关于你的职能的评论:
1.为什么需要第三个参数bool flag
,而不是将它作为局部变量?
2.如果您想展开一个数组,您应该将旧数组复制到新分配的元素中,然后添加新元素,您不能只做:*myArray = element;
3.如果要迭代数组长度/大小,而不是:
for (int i = 0; i < strlen(*myArray) ; ++i)
向函数传递一个附加参数,该参数指示数组中的元素数。
使用std::string
和std::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";
}
https://stackoverflow.com/questions/34387181
复制