c++


Lambda and map, param by reference - compile error


I've tried to narrow down my problem to a minimal example:
#include <algorithm>
#include <map>
#include <string>
#include <vector>
int main()
{
std::vector<int> result;
std::map<std::string, std::pair<unsigned int, std::vector<int>>> other;
if (true)
{
std::for_each(other.begin(), other.end(),
[&](std::pair<std::string, std::pair<unsigned int, std::vector<int>>> & data)
{
result.insert(result.end(), data.second.second.begin(), data.second.second.end());
});
}
return 0;
}
I get a compiler error:
error C2664: 'void main::<lambda_1b93236899a42921c1aec8d5288e5b90>::operator ()(std::pair<std::string,std::pair<unsigned int,std::vector<int,std::allocator<_Ty>>>> &) const': cannot convert argument 1 from 'std::pair<const _Kty,_Ty>' to 'std::pair<std::string,std::pair<unsigned int,std::vector<int,std::allocator<_Ty>>>> &'
As far as I can tell the lambda parameter is indeed a reference to the type that is contained by the map which we are iterating through. That is the type I am supposed to be using, right?
If I remove the amperstand before data it compiles.
Why?
I do not want to pass each element by value, as those collections will contain a lot of data in my real program.
If I replace the lamda param with auto & it compiles, which leads me to believe the type in the lamda param does not match the type contained by the map, but it sure looks like it does to me. Also, why would the original compile without & if the type is wrong?
What am I missing/not understanding?
std::map<Key, T>'s value_type is std::pair<const Key, T>, not std::pair<Key, T>. The version without an ampersand makes a copy of each pair. Since you can copy const Key to Key everything is fine. Add a const to your lambda's parameter type.
#include <algorithm>
#include <map>
#include <string>
#include <vector>
int main()
{
std::vector<int> result;
std::map<std::string, std::pair<unsigned int, std::vector<int>>> other;
if (true)
{
std::for_each(other.begin(), other.end(),
[&](std::pair<const std::string, std::pair<unsigned int, std::vector<int>>> & data)
// Add this const ^^^^^
{
result.insert(result.end(), data.second.second.begin(), data.second.second.end());
});
}
return 0;
}
I've been strugglig with the very same problem today.
I solved that making the key value type in the std::pair const:
[&](std::pair<const std::string, std::pair<unsigned int, std::vector<int>>> & data)
// ^^^^^
After thinking about that a bit, it's quite logical:
You cannot change the key_value of a std::map's entry to something different. So if it's working with an auto loop and a reference it needs to be specified as const.
Make the parameter to your lambda "const".

Related Links

Parent variadic function template specialized in child
How does the quality of 128 bit MurmurHash3 change in case of small key length or output truncation?
Raw socket SYN vs. packet socket SYN
How to construct a list of files from the `start group … end group` linker option
How to exclude isolated nodes from generated Doxygen Class Hierarchy
Why might compiling with -march=native cause “pointer being freed was not allocated”?
Cant access correct number of vertices for a 3d model (.OBJ) using Assimp
In using-declaration, can dependent names render to constructors after template substitution?
How to add C++ files to the Objective-C/C++ OpenGL ES project
Using Eigen in custom tensorflow op
Create JSON structure based on input variables
C++ range for loop different than regular for loop [closed]
C++ boost thread causes segmentation fault when instantiated twice
c++ - 3 bears in a vector of a struct, how can I change this code so the specific bear at the exit is removed?
Reading from excel/text file without skipping whitespaces unless made by a tab
How to initialize const size array in constructor without explicitly stating the size in class declaration?

Categories

HOME
.htaccess
hyper-v
data-warehouse
masonry
payment
jupyter-notebook
sql-server-2005
luigi
authorization
bloomberg
uwp-xaml
axis2
wayland
android-animation
iis-8
xhtml
directshow
datagrid
pygtk
spf
translate
vbulletin
shoutem
sourceforge
angularjs-ng-transclude
pthreads
row-number
filenet-p8
pentaho-spoon
android-constraintlayout
gulp-sass
robots.txt
cdb
unimrcp
xmlstarlet
cut
uiinterfaceorientation
revit
vowpalwabbit
fxml
uilabel
affiliate
coupon
c#-to-f#
ggiraph
gearman
street-address
tensorflow-serving
sequences
legacy
nn
pi
android-auto
cartography
nsset
ranorex
getelementsbyclassname
exceljs
erpnext
gear-vr
c++1z
cscope
collaborative-filtering
rtai
spring-social-facebook
cpio
rate
jwrapper
imshow
mapfragment
smf
eclipse-indigo
kendo-datepicker
ratchet
customdialog
mime-mail
anonymity
tvml
r1soft
max-heap
swift-mt
realbasic
stompjs
command-line-tool
busy-waiting
adobe-dps
wordpress-4.5
sql-agent-job
gamma-function
topological-sort
compiler-options
kismet-wireless
wpftoolkit
componentkit
tracker
javascript-databinding
webproxy
hasp
firstdata
nsurlprotocol
google-playground
bitmapimage
styledtext
resharper-7.1
dynamic-html
problem-steps-recorder
c++builder-6
postfix-operator
mindmap
ereg
slimv
file-association
jpreloader
set-theory
java-service-wrapper
customvalidator
wexitstatus
scopes
fibonacci-heap
viewexpiredexception
showmodaldialog
codehighlighter
olpc
trackback
task-tracking
release-builds

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile