字符串数组(字符)的 C++ 元素依赖于源字符串

标签 c++ string

一点背景信息:我正在尝试制作一个非常简单的哈希函数/哈希表,如 described here 。我基本上是第一步,根据数组开头的字母盲目地向数组添加一个键(不检查空间是否被占用)。到目前为止我用来执行此操作的代码:

int main(int argc, char **argv) {
    char *arrayKeys[300];
    std::string aName("Charles");

    char *aNameCpy = new char[aName.size() + 1];
    std::copy(aName.begin(), aName.end(), aNameCpy);
    aNameCpy[aName.size()] = '\0';

    int kPos = storeKey(arrayKeys, aNameCpy);

    std::cout << "The new position in arrayKeys for 'Charles' is:  " <<
        kPos << "\ncontaining the text: " << arrayKeys[kPos] << std::endl;
    delete[] aNameCpy;  
    return 0;
}

int storeKey(char **keys, char *key) {

    int charLett = -1;
    charLett = (int)key[0];
    if(charLett != -1)
        charLett = charLett - 65;

    keys[charLett * 10] = key;

    return charLett*10;
}

我的问题是,如何将字符串添加到数组(arrayKeys)中,使其完全独立于数组,而不依赖于原始字符串?如果我在打印数组键之前删除字符串的拷贝(aNamCpy),数组键就会变成乱码。我在将字符串发送到函数之前复制该字符串,因为我需要一个非常量字符串添加到 arrayKeys 数组(以便可以修改它),并且我查看的任何字符串方法似乎都会返回 const。

(我尝试的另一个版本可以是 found here ,但我不想像那样初始化 arrayKeys - 具有明确的第二维(字符串)长度)
C++ 对我来说仍然很新,所以我不知道如何通过将字符串复制到 arrayKeys 来处理非常量部分。任何帮助将非常感激。

最佳答案

以下是我如何更改代码以使用更现代的 C++ 结构。我想您会发现这种方式更容易使用。

int storeKey(vector<string> &keys, const string &key) {
    int charLett = -1;

    if (!key.empty()) {  // you weren't doing this before!
        charLett = key[0];
        charLett = toupper(charLett) - 'A';
        keys[charLett * 10] = key;
    }

    return charLett*10;
}

int main() {
    vector<string> arrayKeys(300);
    std::string aName("Charles");

    // No need to bother with the awkward copying.
    // std::vector and std::string will take care of it for us.

    int kPos = storeKey(arrayKeys, aName);

    if (kPos >= 0) {
        cout << "The new position in arrayKeys for 'Charles' is:  " <<
            kPos << "\ncontaining the text: " << arrayKeys[kPos] << endl;
    }

    // Don't have to remember to delete anything because nothing was new'ed.
    return 0;
}

关于字符串数组(字符)的 C++ 元素依赖于源字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8619730/

相关文章:

c++ - 如何检查矩阵中是否有重复数字 C++

c++ - 使用更扁平模式的性能影响

c++ - 持续集成测试插件系统 |特拉维斯CI

javascript - 在正则表达式 Javascript 中获取内部字符串前后的字符串

Python 迭代切片日期字符串列表的最快方法

c++ - 如何将函数作为参数传递给transform()函数?

C++:使用一对 (cpp_int, int) 整数作为 unordered_map 中的键(其中 cpp_int 是 boost 多精度整数)

php - 搜索字符串(变量匹配)并打印

javascript - 使用 jQuery 将复杂的标点字符串拆分为大于 2 个字符的常规单词

python - Python2中如何将字符串转换为字节?