简体   繁体   English

检查映射中是否存在键,然后更新值

[英]checking if key exist in map then updating value

In my project I want to insert keys to a map. 在我的项目中,我想向地图插入关键点。 All new keys should get the value 1.0, but existing keys should be incremented by 1. 所有新键的值都应为1.0,但现有键的值应增加1。

Here's the code 这是代码

vector <string> pairs; 
map<string, float> two;
map <string, float>::iterator it;

string a = "a";
string b = "b";
string c = "a";

pairs.push_back(a);
pairs.push_back(b);
pairs.push_back(c);

for(int i=0; i<pairs.size(); i++)
{
    it = two.find(string(pairs[i]) );
    if(i==0)
    {
        two[string(pairs[i])]=1.0;
    }
    else if ( it == two.end() ) 
    {
        it->second = it->second + 1.0;
    //after this line ^,my compiler stop working
    }
    else
    {
        two[string(pairs[i])]=1.0;
    }
}

After this, the object should be 在此之后,对象应该是

a  2
b  1

How can I do so. 我该怎么办。

else if ( it == two.end() ) 
    {
        it->second = it->second + 1.0;

Above line of code need to correct as follows 上面的代码行需要更正如下

else if ( it != two.end() ) 
             ^^^
    {
        it->second = it->second + 1.0;

More than that: 比那更多的:

it = two.find(string(pairs[i]) );

Above line can rewrite as follows 上面的行可以重写如下

it = two.find(pairs[i] );

The STL was designed to do this efficiently, and it pays to see how. STL旨在有效地做到这一点,并且值得一看。

But first, note that in your code, the lines 但首先,请注意在代码中

two.find(string(pairs[i]) );

two[string(pairs[i])]=1.0;

perform two lookups, which is a bit of a waste. 执行两次查找,这有点浪费。

If you look at the signature for map::insert , you can see that the return value is std::pair<iterator, bool> . 如果查看map::insert签名 ,则可以看到返回值是std::pair<iterator, bool> The second is a boolean indicating whether the element was actually inserted. 第二个是布尔值,指示是否实际插入了元素。 The first is an iterator to either the previous element (if it existed, in which case it was not overwritten), or to the new element. 第一个是对先前元素(如果存在,在这种情况下未被覆盖)的迭代器,或对新元素的迭代器。

So, the way to do it efficiently is to write 因此,有效执行此操作的方法是编写

auto ins = two.insert(make_pair(pairs[i], 0));
ins.first->second += 1;

The easiest and most efficient solution is: 最简单,最有效的解决方案是:

for (auto const& s :  pairs) two[s] += 1.0;

This works because the [] operator on maps automatically creates an entry if the key isn't present, using the default value constructor. 之所以可行,是因为如果没有键,则地图上的[]运算符会使用默认值构造函数自动创建一个条目。 For floats, the default constructor produces a 0.0. 对于浮点数,默认构造函数产生0.0。

Since [] returns a reference, no additional lookup will be done in order to increment the value. 由于[]返回引用,因此不会进行其他查找来增加值。

There should be it != two.end() instead of it == two.end() 应该是!= two.end()而不是== two.end()

I think also the 1st condition (i==0) checking can be skipped 我认为也可以跳过第一个条件(i == 0)检查

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

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