c++ - 如何在包含char和pair<int,string>的map中按键删除元素

标签 c++ c++11 stl

我想删除所有先配对 == 0 的元素

这里代码:

int main()
{
    map<char, pair<int,string>> myMap;
    map<char, pair<int,string>>::const_iterator it;
    for (int i = 0; i < 10; i++)
    {
        char c = 'a' + i;
        pair<int,string> p = make_pair(rand() % 2, "dd");
        myMap.insert(make_pair(c,p));
    }

    it = find_if(myMap.begin, myMap.end(), isEqual);

}

bool isEqual(const pair<char, pair<int, string> > element)
{
    return element.second.first == 0;
}

错误:

/usr/include/c++/4.8/bits/stl_algo.h:150: error: could not convert '__first.std::_Rb_tree_iterator<_Tp>::operator*<std::pair<const char, std::pair<int, std::basic_string<char> > > >()' from 'std::pair<const char, std::pair<int, std::basic_string<char> > >' to 'std::pair<int, std::basic_string<char> >'

   while (__first != __last && !bool(__pred(*__first)))

最佳答案

当然可以。

我想我会写这样的代码(我添加了一些额外的代码来打印删除前后 map 的内容以表明它有效):

#include <map>
#include <utility>
#include <iostream>
#include <stdlib.h>
#include <string>
#include <algorithm>
#include <iterator>
#include <vector>

using namespace std;

ostream &operator<<(ostream &os, pair<int, string> const &p) {
    return os << "[" << p.first << ", " << p.second << "]";
}

int main() {
    map<char, pair<int, string>> myMap;
    for (int i = 0; i < 10; i++) {
        char c = 'a' + i;
        pair<int, string> p = make_pair(rand() % 2, "dd");
        myMap.insert(make_pair(c, p));
    }

    std::cout << "before:\n";
    for (auto const &p : myMap)
        std::cout << p.first << ": " << p.second << "\n";

    map<char, pair<int, string> >::iterator it;
    while (myMap.end() != (it = find_if(myMap.begin(), myMap.end(), [](auto p) { return p.second.first == 0; })))
        myMap.erase(it);

    std::cout << "\nafter\n\n";
    for (auto const &p : myMap)
        std::cout << p.first << ": " << p.second << "\n";

}

关于c++ - 如何在包含char和pair<int,string>的map中按键删除元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32151182/

相关文章:

c++ - 在没有信道数据包丢失的传输中未收到数据包的原因?

c++ - 使用函数指针将字符串数组作为参数传递

C++ STL pop 不返回

c++ - 如何离开循环

c++ - SFML- sleep 计算

c++ - 为什么 lambda 的调用运算符隐式为 const?

c++ - C++11 中的空白比预处理标记分​​离更多?

c++ - 如何在 C++ 代码中要求某些概念?

c++ - 控制 std::vector 重新分配

c++ - vc90 上的 jsoncpp?