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

C++ getting “invalid user-defined conversion” error
Compiler Errors in atlwin.h
How to use a vector of shared pointers to ojbects
ld.exe||cannot open output file bin\Debug\<FILENAME>.exe Permission denied [C++]
strange bug with huffman decoding tree
UVC Extension Unit and Directshow Integration
Memory Leak In C++ Graph Function (valgrind not specific on line)
How to add and use .zip (or .pak) files to c++ project?
Calling virtual function in derived class
Open hdf5 string dataset
Segmentation fault - why and how does it work?
passing non-const object for const input parameter?
deserializing by function pointer, but can't get the syntax right
“no matching function” initializing class
Code compiles and links but does not run (at all, loading libraries fails)
Architecture-generic InterlockedIncrement for 32/64-bit

Categories

HOME
angular
datatables
google-analytics
sails.js
selenium-webdriver
less
ignite
uitableview
chromium
visual-foxpro
sage
formula
delaunay
lokijs
jspdf
sql-azure
jquery-gmap3
pentaho-spoon
react-boilerplate
moshi
visualvm
sitefinity
structured-data
autoload
geckofx
radio
word
regex-negation
artoolkit
uwamp
winrt-xaml
userfrosting
ngrx-effects
ansible-vault
singleton-type
paypal-adaptive-payments
ranorex
http-status-code-415
smartmeter
optional
cscope
helium
self-referencing-table
ms-project-server-2013
parrot
compass
kendo-datepicker
virtual-directory
arithmetic-expressions
android-selector
numerical-analysis
little-endian
mime-mail
polymer-designer-tool
wx
ti-nspire
apache-commons
qubole
smslib
uiactivity
microsoft.mshtml
determinants
ironscheme
date-arithmetic
grunt-contrib-cssmin
compiler-options
rgs
file-attributes
comfortable-mexican-sofa
appcompat-v7-r22.1
casbah
worklight-server
openacs
restkit-0.20
kiwi
firstdata
println
application-integration
styledtext
topcoat
postfix-operator
.class-file
customvalidator
static-array
memory-mapped-files
struts-config
getprocaddress
mobile-phones
codeigniter-datamapper
soaplite
cocos2d-python
viewexpiredexception
application-design
xla
flashlite

Resources

Mobile Apps Dev
Database Users
javascript
java
csharp
php
android
MS Developer
developer works
python
ios
c
html
jquery
RDBMS discuss
Cloud Virtualization
Database Dev&Adm
javascript
java
csharp
php
python
android
jquery
ruby
ios
html
Mobile App
Mobile App
Mobile App