首页 > 解决方案 > 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)。

从来没有遇到过这样的问题。任何想法?

谢谢指教。

标签: c++stliteratorc++17stl-algorithm

解决方案


在这一行:

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>


推荐阅读