std::fill 无法与关联容器一起使用,比如 std::map?为什么?

问题描述 投票:0回答:1

cppreference
中有std::fill这样的声明:

template< class ForwardIt, class T >
void fill( ForwardIt first, ForwardIt last, const T& value );

但是我不明白为什么它不能用于

std::map
。因为cppreference没有说它不能应用于
std::map
,我真的很清楚为什么。这是演示代码

#include <algorithm>
#include <iostream>
#include <map>
 
int main()
{
    std::map<int, int> v {{1, 1}, {2, 2}, {3, 4}};
 
    std::fill(v.begin(), v.end(), {666, 666});
 
    for (auto pair : v)
        std::cout << "{" <<pair.first << pair.second << "}" << ' ';
    std::cout << '\n';
}

这是编译器抱怨的内容:

g++ -std=c++20 -O2 -Wall -pedantic -pthread main.cpp && ./a.out
main.cpp: In function 'int main()':
main.cpp:9:14: error: no matching function for call to 'fill(std::map<int, int>::iterator, std::map<int, int>::iterator, <brace-enclosed initializer list>)'
    9 |     std::fill(v.begin(), v.end(), {666, 666});
      |     ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/local/include/c++/13.1.0/algorithm:60,
                 from main.cpp:1:
/usr/local/include/c++/13.1.0/bits/stl_algobase.h:1000:5: note: candidate: 'template<class _ForwardIterator, class _Tp> constexpr void std::fill(_ForwardIterator, _ForwardIterator, const _Tp&)'
 1000 |     fill(_ForwardIterator __first, _ForwardIterator __last, const _Tp& __value)
      |     ^~~~
/usr/local/include/c++/13.1.0/bits/stl_algobase.h:1000:5: note:   template argument deduction/substitution failed:
main.cpp:9:14: note:   couldn't deduce template parameter '_Tp'
    9 |     std::fill(v.begin(), v.end(), {666, 666});
      |     ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
In file included from /usr/local/include/c++/13.1.0/algorithm:73:
/usr/local/include/c++/13.1.0/pstl/glue_algorithm_defs.h:191:1: note: candidate: 'template<class _ExecutionPolicy, class _ForwardIterator, class _Tp> __pstl::__internal::__enable_if_execution_policy<_ExecutionPolicy, void> std::fill(_ExecutionPolicy&&, _ForwardIterator, _ForwardIterator, const _Tp&)'
  191 | fill(_ExecutionPolicy&& __exec, _ForwardIterator __first, _ForwardIterator __last, const _Tp& __value);
      | ^~~~
/usr/local/include/c++/13.1.0/pstl/glue_algorithm_defs.h:191:1: note:   template argument deduction/substitution failed:
main.cpp:9:14: note:   candidate expects 4 arguments, 3 provided
    9 |     std::fill(v.begin(), v.end(), {666, 666});
      |     ~~~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
c++ c++11
1个回答
0
投票

地图数据(节点)的存储元素是

value_type
。对于
map<Key,T>::value_type
std::pair<const Key,T>
,因此您无法更改现有节点中的
Key
。您必须删除旧元素并创建新元素。
fill
确实会覆盖现有的任务,它只是一个错误的工具,因为关联容器必须自己管理这些任务。

还存在每次更改后迭代器失效的问题。虽然 C++17 添加了

map::insert
(允许插入节点)和
insert_or_assign
,而 C++23 添加了
insert_range

`

© www.soinside.com 2019 - 2024. All rights reserved.