2017-06-06 55 views
0
#include <vector>                

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

結果我得到捕捉陣列使元素常量

main.cc:5:45: error: passing ‘const std::vector’ as ‘this’ argument of ‘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]’ discards qualifiers [-fpermissive] auto funct = test{ test[0].push_back(1); };

我如何能捕捉test指針未做其價值const?除了使其成爲vector<vector<int>>之外,還有其他方法嗎?爲什麼它甚至成爲一個常量?

+0

並且不是直接重複:'test'不是指針_。這是一個數組。有很多情況下數組會衰減指針,但這不是其中之一(並且您的數組是通過值複製的)。 – Useless

回答

1

你可以試試這個。

#include <vector>                

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

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