C++ 循环中断,因为 std::find 算法

C++ loop breaked 'cause the std::find algorithm

我有下一个 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]);
    }
}

我正在遍历 const char*,寻找可能位于 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>