【问题标题】:Capturing array of vectors in lambda makes elements const [duplicate]在 lambda 中捕获向量数组使元素成为 const [重复]
【发布时间】:2017-06-06 09:52:54
【问题描述】:
#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 std::vector<_tp _alloc>::push_back(std::vector<_tp _alloc>::value_type&&) [with _Tp = int; _Alloc = std::allocator; std::vector<_tp _alloc>::value_type = int]' 丢弃限定符 [-fpermissive] 自动功能=测试{测试[0].push_back(1); };

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

【问题讨论】:

  • 还有一点不是直接重复:test 不是指针。这是一个数组。数组衰减为指针的情况有很多,但这不是其中之一(并且您的数组是按值复制的)。

标签: c++ c++11


【解决方案1】:

你可以试试这个。

#include <vector>                                                               

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

【讨论】:

    【解决方案2】:
    #include <vector>                                                               
    
    int main() {                                                                   
      std::vector<int> test[2];                                                     
      auto funct = [test]() mutable { test[0].push_back(1); };                               
      funct();                                                                      
    } 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-15
      • 1970-01-01
      • 1970-01-01
      • 2015-01-19
      • 2017-06-22
      相关资源
      最近更新 更多