在lambda中捕获向量数组使元素成为const

时间:2017-06-06 09:52:54

标签: c++ c++11

#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'作为'void'参数传递给'void std :: vector&lt; _Tp,_Alloc&gt; :: push_back(std :: vector&lt; _Tp,_Alloc&gt ; :: value_type&amp;&amp;)[with _Tp = int; _Alloc = std :: allocator; std :: vector&lt; _Tp,_Alloc&gt; :: value_type = int]'丢弃限定符[-fpermissive]      auto funct = test {test [0] .push_back(1); };

如何捕获test指针而不使其值const?除了使它成为vector<vector<int>>之外,还有其他方法吗?为什么它甚至成为一个常量?

2 个答案:

答案 0 :(得分:1)

#include <vector>                                                               

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

答案 1 :(得分:1)

你可以试试这个。

#include <vector>                                                               

int main() {                                                                   
  std::vector<int> test[2];                                                     
  auto funct = [&test](){ test[0].push_back(1); };                               
  funct();
  return 0;                                                                      
} 
相关问题