在lambda中捕获各种向量使元素const

Capturing array of vectors in lambda makes elements const

本文关键字:向量 元素 const lambda      更新时间:2023-10-16
#include <vector>                                                               
void main() {                                                                   
  std::vector<int> test[2];                                                     
  auto funct = [test](){ test[0].push_back(1); };                               
  funct();                                                                      
} 

结果我得到了

main.cc:5:45:错误:传递'const std :: vector'as'void std :: vector&lt; _tp,_alloc> :: push_back(std :: vector&lt; _tp,_tp,_alloc,_alloc,_alloc,_alloc,_alloc,_alloc,_alloc,_alloc,_alloc> :: value_type&amp;&amp;([with _tp = int;_alloc = std ::分配器;std :: vector&lt; _tp,_Alloc> :: value_type = int]’丢弃预选赛[-fpermissive] auto funct = test {test [0] .push_back(1(;};

如何在不制作其值const的情况下捕获test指针?除了使其成为vector<vector<int>>以外,还有其他方法吗?为什么它甚至成为const?

您可以尝试此。

#include <vector>                                                               
int main() {                                                                   
  std::vector<int> test[2];                                                     
  auto funct = [&test](){ test[0].push_back(1); };                               
  funct();
  return 0;                                                                      
} 
#include <vector>                                                               
int main() {                                                                   
  std::vector<int> test[2];                                                     
  auto funct = [test]() mutable { test[0].push_back(1); };                               
  funct();                                                                      
}