简体   繁体   English

遍历std映射并比较文本

[英]Iterating over a std map and comparing text

I am currently something something like this 我目前是这样的

std::map<std::string,std::string>::iterator it ;
for(it=mmap.begin();it!=mmap.end();it++)
{
    if(it->second.c_str() != "qa" && it->second.c_str() != "qb")
    {
        //Entered
    }
}

Now the problem with this code is that it goes into the entered section even when the iterator is 现在,此代码的问题在于,即使迭代器为

it("Testing this","qb")

Thee above means that it->second = "qb" 上面的Thee表示it->second = "qb"

Now my question is why is the code going ino the if statement if it->second = "qb" My thought is that it should not have because the conditional statment part is it->second.c_str() != "qb" 现在我的问题是,如果it->second = "qb" ,代码为什么会进入if语句中呢?我的想法是它不应该这样,因为条件语句部分是it->second.c_str() != "qb"

The problem is because it->second.c_str() != "qa" is not the correct way to compare C strings (it compares pointers and not the string contents). 问题是因为it->second.c_str() != "qa"不是比较C字符串的正确方法(它比较指针而不是字符串内容)。 You however do not need to convert to a C string first before comparing as you can compare the strings directly with: it->second != "qa" . 但是,您无需在进行比较之前先转换为C字符串,因为您可以将字符串直接与以下内容进行比较: it->second != "qa" If you for some reason need to use the c string with c_str() then you will need to use strcmp . 如果出于某种原因需要将c字符串与c_str()一起使用,则需要使用strcmp

c_str() is a character array (pointer), so you are comparing two pointers which are different. c_str()是一个字符数组(指针),因此要比较两个不同的指针。

Use string objects instead: 使用字符串对象代替:

std::string QA("qa");
std::string QB("qb");
std::map<std::string,std::string>::iterator it ;
for(it=mmap.begin();it!=mmap.end();it++)
{
    if(it->second != QA && it->second  != QB)
    {
        //Entered
    }
}

or actually do C style string compare: 或者实际上是比较C样式的字符串:

    if ( strcmp(it->second.c_str(), "qa") != 0 && strcmp(it->second.c_str(), "qb") != 0 )

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM