如何在数组中找到第n个元素?

时间:2019-11-20 18:35:23

标签: c++

这是我的功能:

string *textRows = nullptr;

string getElement(int index) const {
    if (index < sizeof(textRows)) {
        return textRows[index];
    }
    return "";
};

当索引大于textRows的长度时,应返回“”。此代码无法按预期方式工作。您有解决方案还是看到我的错误?

1 个答案:

答案 0 :(得分:2)

您对sizeof有一个严重的误解。 它不返回数组的大小,但返回类型的大小。因此sizeof(textRows)将返回string *的大小,该大小与任何指针的大小相同,通常为4或8个字节。

在标准C ++中,如果只有一个指针,则无法检索数组的大小。因此,我建议您将c样式数组替换为c ++样式std::vector

std::vector<std::string> textRows;

void fillTextRows()
{
    //Use push_back to fill the vector:
    textRows.push_back("...");
}

std::string getElement(int index) const {
    if (index < textRows.size()) {
        return textRows[index];
    }

    return "";
};

或者,如果确实需要,必须使用指针:记住数组的大小。

std::string *textRows = nullptr;
size_t textRowsLen = 0;

void fillTextRows(size_t count)
{
    textRowsLen = count;
    textRows = new std::string[count];

    //put some data in there:
    textRows[0] = "...";
}

std::string getElement(int index) const {
    if (index < textRowsLen) {
        return textRows[index];
    }

    return "";
};

从本质上讲,这是在彻底改变方向,因为std::vector是为了完全抽象这种情况而设计的。

相关问题