当您在此单词中搜索单词时调整字符数组的大小?
Resize a char array when you search a word in this one?
我正在尝试像这样调整字符数组的大小(使用搜索算法(:
char* items[] = { "apple", "apple_2", "banana", "orange" };
当我搜索例如"app"、"appl"、"people"时,我想像这样调整字符数组的大小:
char* items[] = { "apple", "apple_2" };
例如,仅使用包含"app"、"appl"的单词,如果我搜索"a",我的字符数组不会移动,因为我示例中的所有单词都包含"a";
我不确定我是否真的清楚。提前感谢您的帮助!对不起我的英语!
C++中的静态数组无法在运行时调整大小。 为了实现您的目标,请查看std::vector
标准容器。它可以动态更改其大小。
下面是如何实现任务的示例:
#include <iostream>
#include <vector>
std::vector<std::string> filter(const std::vector<std::string>& strings, const std::string& pattern)
{
std::vector<std::string> matchItems;
for (const auto& elem : strings)
{
if (elem.find(pattern) != std::string::npos)
{
matchItems.push_back(elem);
}
}
return matchItems;
}
int main()
{
std::vector<std::string> v { "apple", "apple_2", "banana", "orange" };
auto filtered = filter(v, "app");
for (const auto& elem : filtered)
{
std::cout << elem << " ";
}
return 0;
}
更重要的是,使用原始char*
和数组是相当老式的。 在现代C++中,您应该使用std::string, std::vector, std::array
希望对您有所帮助!
除非有很好的理由使用char *
数组(如果有,请指出该原因,我将尝试在我的答案中容纳它(,否则您应该尝试使用该语言的功能。
#include <vector>
#include <string>
#include <algorithm>
int main (int argc, char **argv) {
std::vector<std::string> items{ "apple", "apple_2", "banana", "orange" };
std::string test_value{"app"};
auto new_end = std::remove_if(items.begin(), items.end(),
[&test_value](auto idx)->auto {
return idx.find(test_value) == std::string::npos;
});
items.erase(new_end, items.end());
return 0;
}
首先,我们使用std::vector<std::string>
来存储值。正如已经指出的那样,调整数组大小是有问题的。然后使用定义的test_value
STL 库函数std::remove_if
和 lambda,我们可以将所需的值收集到vector
的开头。然后items.erase()
截断矢量。
要保持原始items
不变:
#include <vector>
#include <string>
#include <algorithm>
int main (int argc, char **argv) {
std::vector<std::string> items{ "apple", "apple_2", "banana", "green apple", "orange" };
std::string test_value{"app"};
std::vector<std::string> selected_items;
std::copy_if(items.begin(), items.end(), std::back_inserter(selected_items),
[&test_value](auto idx)->auto {
return idx.find(test_value) != std::string::npos;
});
return 0;
}
相关文章:
- 指向指向字符数组的指针数组的指针
- 比较字符数组
- 如何使用Crypto++并为RSA返回可打印的字节/字符数组
- 使用无符号字符数组有效存储内存
- 按字符值访问int数组
- 错误:字符数组的初始值设定项太多
- 对字符数组中的元素执行逐位操作
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++ 无法在字符数组中使用 for 循环打印字母模式
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 移动二维数组中的字符
- C++ 传递二维字符数组
- 无法在 C++ 中输入字符数组
- C++ 带结构的数组字符
- 数组字符包含量超出预期
- 读取文件并添加到数组字符
- 如何在Qt中更改或替换数组字符
- 为什么编译器不在参数中传递数组字符 *arr[] 的大小?
- 井字棋数组字符错误
- 分割数组字符