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

leveldb log_reader.h/Reader class design consideration
My linked lists program terminated with status -1073741819 In Code blocks compiler(x0000000005)) [closed]
Why does this double mutex lock not cause deadlock?
Helper function declaration outside class?
Auto declaration of map iterator error on GCC
Finding the length of a C style char * string in c++ [duplicate]
How to draw square on the button at the center using OpenGL?
How to use pthread to write a C++ class like “boost::shared_mutex”
Undefined reference to a superclass' virtual function
How many ways can fill in HxW rooms with 2x1 tatami mats? [closed]
CMake add_subdirectory not invoking the child CMakeLists.txt
How to explicitly get linear indices from arrayfire?
cppunit throws std::bad_alloc after upgrading gcc to 5.4.0
Program compiles but I think switch is ignored.
multiplication of two integer arrays
get and set Enum variable inside a class?

Categories

HOME
perl
reporting-services
data-warehouse
wildfly
text
set
python-3.6
ibm-mobilefirst
wayland
openmeetings
zk
pthreads
double
photon
cassandra-cli
smt
clang-format
odbc
divide-and-conquer
konvajs
firebase-cloud-messaging
code-injection
osx-elcapitan
face-api
google-surveys
mpeg
u2
footable
remote-connections
geckofx
puma
gmail-contextual-gadgets
state
nsdate
product-key
nsubstitute
webex
angular2-http
predict
inline
ios6
ffi
case-sensitive
masm
appharbor
javac
proof-of-correctness
jsdoc3
heyzap
graylog
rpy2
code-signing-entitlements
vibration
twebbrowser
git-stash
apple-watch-complication
little-endian
liquibase-hibernate
html5builder
xamarin-forms
typescript1.7
protractor-net
aloha-editor
html5-template
reagent
ironscheme
grunt-contrib-cssmin
rot13
comfortable-mexican-sofa
string-search
usleep
aglio
facade
mashup
maptiler
iron
socketrocket
phpmotion
commission-junction
ldapconnection
customvalidator
system-design
ora-01426
wymeditor
abbreviation

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