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

generate all possible combinations of n bit binary numbers wherein k bits are always set using backtracking only
How Can I Use a Single Codebase for Unreal and Unity 3D?
OpenGL glDrawBuffer and glBindTexture
Get angle from x,y of a linear base of an object
Replace the loops to insert and update a collection by the Standard Library
How to write code results (that are within a void function) to a text file in C++
Qt Data Visualization: How to integrate a Q3DScatter graph into a Widget in a Main Window?
Webcam disabled by AVG antivirus
Visual studio 2017 and the cl.exe error
“greater” functor gives compiler error
Trying to use the standard (from STL) function count_if [duplicate]
Boost thread.hpp include error
Linux: Content of /dev/fb0 not displayed to screen as expected
Reading .txt file into multiple arrays
File handling in C programming: What is the difference between below two codes? [duplicate]
string is not a member of std for specific files

Categories

HOME
machine-learning
github
processing
qt5
loops
inno-setup
powershell-v4.0
datastax
junit
migration
custom-attributes
castle-windsor
speech-recognition
graph-algorithm
xhtml
tensorboard
google-vr
wmi-query
firebreath
amazon-route53
cassandra-cli
denial-of-service
sensenet
systemml
azure-storage-blobs
google-cloud-vision
jsdata
ebcdic
vowpalwabbit
chinese-locale
uilabel
jquery-chosen
gsutil
magnolia
opensaml
psftp
flops
tridion
uicollectionviewcell
ngrx-effects
pivottable.js
card-flip
ats
grayscale
jenkinsfile
google-console-developer
singleton-type
khan-academy
gold-parser
html.dropdownlistfor
nsfontpanel
allegro5
erpnext
django-media
autocompleteextender
nuodb
zoo
vibration
ucp
twebbrowser
review-board
dart-polymer
nested-forms
ienumerable
dotpeek
google-roads-api
splash-screen
payara
mod-jk
unique-constraint
elasticsearch-marvel
uiactivity
qmediaplayer
gamma-function
ncbi
lastaccesstime
android-view
ilias
javascript-databinding
jsqlparser
out
restkit-0.20
dav
rhodecode
iron
activator
interlacing
dbase
postfix-operator
ios6.1
jpreloader
badimageformatexception
enctype
keymando
memory-profiling
plcrashreporter
registrar
wind-river-workbench
endl
google-instant-previews
equivalent
maintenance-plan
vmwaretasks
pointer-arithmetic

Resources

Encrypt Message



code
soft
python
ios
c
html
jquery
cloud
mobile