c++ - C ++循环中断'导致std :: find算法
问题描述
我有下一个 C++ 代码片段:
...
static constexpr const char* my_char_array [10] { // Some literals here... } // Member of a class
std::vector<std::string> splitted_input { // Contains C++ strings }
std::vector<std::string> matched_keywords { // The coincident ones will be copied here }
for (int i = 0; i < sizeof(this->my_char_array); i++) {
std::cout << "Comparing: " << this->my_char*_array[i] << std::endl;
auto value = std::find(splitted_input.begin(), splitted_input.end(), (std::string) this->my_char_array[i]);
if ( value != end(splitted_input) ) {
matched_keywords.push_back(this->keywords[i]);
}
}
我正在遍历 a const char*
,寻找可能在 a 中的文字vec<string>
。当我使用 std::find 算法时,for 循环在第一次迭代时停止(std::cout 只输出第一个值my_char*_array
)。
从来没有遇到过这样的问题。任何想法?
谢谢指教。
解决方案
在这一行:
for (int i = 0; i < sizeof(this->my_char_array); i++) {
您正在使用sizeof
返回占用的字节数的运算符,my_char_array
这等于指针的大小(x64 系统上为 8 个字节)乘以数组中的指针数。因此,此代码迭代的元素比实际数组中的元素更多,这导致了 UB(未定义的行为)。通常的解决方案是除以元素大小:
for (int i = 0; i < sizeof(this->my_char_array)/sizeof(this->my_char_array[0]); i++) {
甚至更好,用 替换数组std::array
,例如:
static constexpr std::array<const char*, 2> my_char_array = {"dsds", "dddd"};
和
for (int i = 0; i < my_char_array.size(); i++) {
不要忘记#include <array>
推荐阅读
- java - Java8 Stream分组与toMap问题
- php - 无法使用codeigniter 4从数据库中获取,插入数据
- python - 在 Dash/Plotly 中显示属性会导致 KeyError
- python - 如何在 Python 中有效地对大型文本语料库使用拼写校正
- docker - dotnet Web 应用程序在 docker 容器中运行,但未处于活动状态
- vb.net - VB.Net 元文件生成错误(“GDI+ 中发生一般错误”)
- excel - 在 Excel 图表上添加垂直线
- php - 获取产品 MPN(制造商部件号)
- cmake - “填充”在 CMake 文档中实际上做了什么?
- r - 根据 R 中的行号重构数据