递归函数中的CPP向量级联

问题描述

我有这个递归函数,该函数不会编译向量级联行处的错误

return newVec.insert(newVec.end(),rightSubArray.begin(),rightSubArray.end());

return leftSubArray.insert(leftSubArray.end(),newVec.begin(),newVec.end());行 给出以下错误

无法转换'newVec.std :: vector :: insert <__ gnu_cxx :: __ normal_iterator vector>>(__ gnu_cxx :: __ normal_iterator (newVec.std :: vector :: end()),rightSubArray.std :: vector :: begin(),rightSubArray.std :: vector :: end()'来自'std :: vector :: iterator {aka __gnu_cxx :: ____ normal_iterator }'到'std :: vector'

也与... when matched then update set earliest_timestamp = least (earliest_timestamp,lEarliest),latest_timestamp = greatest(latest_timestamp,lLatest) where earliest_timestamp > lEarliest or latest_timestamp < lLatest ... 相同。

我确定我用于向量级联的方法是最可靠和更好的方法,但是我无法弄清楚是什么原因导致了错误。我在这里做错什么了吗?

解决方法

调用std::vector::insert返回iterator,而不是修改后的vector。因此,return语句将尝试将iterator转换为vector,从而使您看到编译器错误。

您可以通过将return语句分成两行来解决此问题:

newVec.insert(newVec.end(),rightSubArray.begin(),rightSubArray.end());
return newVec;

您还需要对其他return语句执行类似的操作。