简体   繁体   English

如何将std :: map元素从一个减去另一个并在C ++中更新它

[英]how to subtract std::map elements from one to other and update it in C++

I am trying to subtract the 1st element of the std::map from every other element of that same std::map. 我试图从同一个std :: map的每个其他元素中减去std :: map的第一个元素。 I couldn't find anything about that. 我找不到任何相关的东西。 Is it possible? 可能吗? for example : 例如 :

std::map<char,int> bar;
bar['a']=11; //should be deleted from other elements
bar['b']=22;
bar['c']=33;
bar['d']=44;

std::cout << "bar contains:\n";
for (std::map<char,int>::iterator it=bar.begin(); it!=bar.end(); ++it)
{
  std::cout <<"key: " <<it->first << " Value=> " << it->second << '\n'; //can i delete here??
  //i want to delete value of a from value of b and update the value of b
}
//the new map should be look like as follows
//bar['a']=11; //or may be 0
//bar['b']=11;
//bar['c']=22;
//bar['d']=33;

Any ideas to do it easily with map in c++? 有什么想法用c ++中的map轻松完成吗? Thanks. 谢谢。

C++11 Solution C ++ 11解决方案

You could use std::for_each for this 您可以使用std::for_each

std::for_each(std::next(bar.begin()), bar.end(), [&bar](std::pair<const char, int>& x){ x.second -= bar.begin()->second; });

For example 例如

#include <algorithm>
#include <iostream>
#include <iterator>
#include <map>

int main()
{
    std::map<char,int> bar;
    bar['a']=11;
    bar['b']=22;
    bar['c']=33;
    bar['d']=44;

    std::for_each(std::next(bar.begin()), bar.end(), [&bar](std::pair<const char, int>& x){ x.second -= bar.begin()->second; });

    std::cout << "bar contains:\n";
    for (std::map<char,int>::iterator it=bar.begin(); it!=bar.end(); ++it)
    {
        std::cout << "key: " << it->first << " Value=> " << it->second << '\n';
    }
}

Output ( working demo ) 输出( 工作演示

bar contains:
key: a Value=> 11
key: b Value=> 11
key: c Value=> 22
key: d Value=> 33

And if you want to subtract even the first element from itself, just remove the std::next call and capture the value you want to subtract out, since you're going to modify the first map entry. 如果你想从自身中减去第一个元素,只需删除std::next调用并捕获你想要减去的值,因为你要修改第一个map条目。

auto const sub = bar.begin()->second;
std::for_each(bar.begin(), bar.end(), [&sub](std::pair<const char, int>& x){ x.second -= sub; });

C++03 Solution C ++ 03解决方案

To subtract the first element from everything except the first element itself 第一个元素本身之外的所有内容中减去第一个元素

int value = bar.begin()->second;
std::map<char, int>::iterator it = bar.begin();
std::advance(it, 1);
for (; it != bar.end(); ++it)
{
    it->second -= value;
}

To include the first element 包括第一个元素

int value = bar.begin()->second;
for (std::map<char, int>::iterator it = bar.begin(); it != bar.end(); ++it)
{
    it->second -= value;
}

You simply need to loop over the map and subtract the value associated with the "first" key from each element, storing the result back into the same element. 您只需循环遍历映射并从每个元素中减去与“first”键关联的值,并将结果存储回相同的元素中。 One approach to that is shown below: 其中一种方法如下所示:

Live example at http://coliru.stacked-crooked.com/a/1bc650592027f5f3 http://coliru.stacked-crooked.com/a/1bc650592027f5f3上的实例

#include <iostream>
#include <map>

int main() {
    // Set up the problem...
    std::map<char, int> foo;
    foo['a'] = 11;
    foo['b'] = 22;
    foo['c'] = 33;
    foo['d'] = 44;

    // Obtain the value of the 'a' key...
    const int value = foo['a'];
    // Subtract that value from each element...
    for (auto& element : foo) {
        element.second -= value;
    }

    // Output the map to verify the result...
    for (auto& element : foo) {
        std::cout << element.first << ": " << element.second << "\n";
    }

    return 0;
}

Note that if you loop over the entire map, you need to store the initial value of foo[a] , since you'll zero it during the iterative subtraction. 请注意,如果循环遍历整个地图,则需要存储foo[a]的初始值,因为在迭代减法期间将其归零。 You can avoid this by using iterators and skipping over the first element using eg std::next(foo.begin()) . 您可以通过使用迭代器并使用例如std::next(foo.begin())跳过第一个元素来避免这种情况。 Other answers demonstrate this technique, so I won't duplicate it here. 其他答案演示了这种技术,所以我不会在这里复制它。

You can use standard algorithm std::for_each declared in header <algorithm> 您可以使用标头<algorithm>声明的标准算法std::for_each

If your compiler supports C++ 2014 then the code can look like 如果您的编译器支持C ++ 2014,则代码​​可能如下所示

#include <iostream>
#include <map>
#include <algorithm>
#include <iterator>

int main() 
{
    std::map<char, int> bar;

    bar['a'] = 11;
    bar['b'] = 22;
    bar['c'] = 33;
    bar['d'] = 44;

    for ( const auto &p : bar )
    {
        std::cout << "{ " << p.first << ", " << p.second << " } ";
    }
    std::cout << std::endl;

    if ( !bar.empty() )
    {        
        std::for_each( std::next( bar.begin() ), bar.end(), 
                       [value = ( *bar.begin() ).second] ( auto &p ) { p.second -= value; } );
    }            

    for ( const auto &p : bar )
    {
        std::cout << "{ " << p.first << ", " << p.second << " } ";
    }
    std::cout << std::endl;
}    

The program output is 程序输出是

{ a, 11 } { b, 22 } { c, 33 } { d, 44 } 
{ a, 11 } { b, 11 } { c, 22 } { d, 33 } 

If your compiler supports only C++ 2011 then the main loop in the program can look like 如果您的编译器仅支持C ++ 2011,那么程序中的主循环可能如下所示

if ( !bar.empty() )
{
    auto value = ( *bar.begin() ).second;
    std::for_each( std::next( bar.begin() ), bar.end(), 
                   [value] ( std::pair<const char, int> &p ) { p.second -= value; } );
} 

The same can be done using for example the range based for loop 使用例如基于循环的范围可以完成相同的操作

#include <iostream>
#include <map>

int main() 
{
    std::map<char, int> bar;

    bar['a'] = 11;
    bar['b'] = 22;
    bar['c'] = 33;
    bar['d'] = 44;

    for ( const auto &p : bar )
    {
        std::cout << "{ " << p.first << ", " << p.second << " } ";
    }
    std::cout << std::endl;

    if ( !bar.empty() )
    {        
        auto value = ( *bar.begin() ).second;
        bool first = true;
        for ( auto &p : bar )
        {
            if ( first ) first = !first;
            else p.second -= value;
        }
    }

    for ( const auto &p : bar )
    {
        std::cout << "{ " << p.first << ", " << p.second << " } ";
    }
    std::cout << std::endl;
}    

Also if the element by which all other elements should be decreased is not necessary the first element of the map then you can use the following approach 此外,如果要减少所有其他元素的元素不是映射的第一个元素,那么您可以使用以下方法

#include <iostream>
#include <map>
#include <algorithm>
#include <iterator>

int main() 
{
    std::map<char, int> bar;

    bar['a'] = 11;
    bar['b'] = 22;
    bar['c'] = 33;
    bar['d'] = 44;

    for ( const auto &p : bar )
    {
        std::cout << "{ " << p.first << ", " << p.second << " } ";
    }
    std::cout << std::endl;

    if ( !bar.empty() )
    {
        // the initializer can be any element not only the first one          
        const auto &value = *bar.begin(); 
        for ( auto &p : bar )
        {
            if ( p.first != value.first  ) p.second -= value.second;
        }
    }

    for ( const auto &p : bar )
    {
        std::cout << "{ " << p.first << ", " << p.second << " } ";
    }
    std::cout << std::endl;
}    
int value = bar.begin()->second;

for(std::map<char,int>::reverse_iterator it=bar.rbegin(); it != bar.rend(); it++) {
    it->second -= bar.begin()->second;
}
bar.begin()->second = value;

暂无
暂无

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

相关问题 如何将 std::unordered_map 向量元素从一个减去另一个并在 C++ 中更新它? - How to subtract std::unordered_map vector elements from one to other and update it in C++? 如何在地图C ++中更新元素的值 - How to update values of elements in map C++ 从向量C ++中的元素中减去值 - subtract values from elements in a vector C++ 如何迭代 std::list,而其他线程在 C++ 中从中删除元素? - How to iterate over std::list, while other thread remove elements from it in C++? 如何从另一个地图键中减去一个地图键列表并获取新地图(地图A - mab B =地图C) - How to subtract one list of map keys from another and get new map (map A - mab B = map C) C++ 如何以结构作为值正确插入和读取 std::map? - C++ How does one insert to, and read from std::map with struct as value correctly? idiomatic C ++,用于从std :: map的最后n个元素创建std :: vector - idiomatic C++ for creating a std::vector from the last n elements of a std::map 我该如何遍历std :: map中的元素 <std::string,shared_ptr<A> &gt;在C ++中 - how to do i iterate through elements of in std::map<std::string,shared_ptr<A>> in c++ 声明一个 C++ std::list,其中的元素指向列表中的其他元素 - Declare a C++ std::list with elements that point to other elements in the list 从C ++中另一个向量中包含的另一个向量中删除所有元素? - Removing all elements from one vector that are contained in the other in C++?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM