C++ STL 映射无法识别 key

标签 c++ stl map

我有这段代码,CBString 只是我用于某些处理的字符串类

  char * scrummyconfigure::dosub(strtype input)
  {
    CBString tstring;
    tstring = input;
    uint begin;
    uint end;

    begin = tstring.findchr('$');
    end = tstring.findchr('}',begin);        

    CBString k = tstring.midstr(begin+2,end-2); // this is BASE
    strtype vname = (strtype) ((const unsigned char*)k);
    strtype bvar = (strtype) "BASE";
    assert(strcmp(bvar,vname) == 0); // this never fails
    // theconf is just a struct with the map subvars
    // subvars is a map<const char *, const char *>
    out(theconf->subvars[bvar]); // always comes up with the value
    out(theconf->subvars[vname]); // always empty

    uint size = end - begin;
    tstring.remove(begin, size);

    return (const char *)tstring; // it's OKAY! it's got an overload that does things correctly
    //inline operator const char* () const { return (const char *)data; } <-- this is how it is declared in the header of the library
  }

为什么 strcmp 总是说字符串相同,但只有我声明为 bvar 的变量返回任何内容?

最佳答案

我假设 strtype 是按以下方式定义的:

typedef char * strtype

您的问题是您假设 vname 和 bvar 具有相同的值,而实际上,它们具有不同的值,每个值都指向包含相同数据的内存块。

std::map 愚蠢地将它们与 == 进行比较,我敢打赌您会发现,如果将它们与 == 进行比较,您会如预期的那样得到 false。您为什么不使用 std::string 类?

编辑:我重写了你的方法以减少恐惧:

// implied using namespace std;
string ScrummyConfigure::removeVariableOrSomething(string tstring)
{
    uint begin; // I'll assume uint is a typedef to unsigned int
    uint end;

    begin = tstring.find('$', 0);
    end = tstring.find('}', begin);        

    string vname = tstring.substr(begin + 2, end - 2); // this is supposedly BASE
    assert(vname == "BASE"); // this should be true if vname actually is BASE

    out(this->conf->subvars[bvar]);  // wherever theconf used to be, its now a member
    out(this->conf->subvars[vname]); // of ScrummyConfigure and its been renamed to conf

    uint size = end - begin;
    tstring.erase(begin, size);

    return tstring; // no casting necessary
}

关于C++ STL 映射无法识别 key ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11660593/

相关文章:

c++ - 将 vector<T> 转换为 initializer_list<T>

c++ - vector <int> 输入和输出

javascript - jQuery .each() 与 .map() 不返回

c++ - std::multimap<key, value> 和 std::map<key, std::set<value>> 有什么区别

c++ - c++ 标准是否指定如何将此指针传递给成员函数?

c++ - 为什么 lambda 取变量的初始值

c++ - 无法将矩阵转换为四元数并返回

java - Map<?, ?> 在 Java 中是什么意思?

c++ - 为什么编译器不能优化 std::string concat?

c++ - 如何获取结构中的位数组?