简体   繁体   中英

" not captured " Error in std::all_of() C++

When I use value in all_of pred function it works but when I use variable it gives error. Whyy??

#include <iostream>
#include <algorithm>
#include <bits/stdc++.h>

using namespace std;

int main()
{
   vector<int> a{1,2,3,4,5,6,7};
   
   int x=10;
   
   if(std::all_of(a.cbegin(),a.cend(),[](int i){return i< x; }))
   {
       cout<<"all elements are smaller than x";
   }
   
   return 0;
}

It Gives error but this doesn't.

if(std::all_of(a.cbegin(),a.cend(),[](int i){return i< 10; }))

You need to capture your variables inside your lambda:

if(std::all_of(a.cbegin(),a.cend(),[x](int i){return i< x; }))
//                                  ^ here

This captures x by value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM