最近我遇到了一个场景,我必须使用其他 vector 的一部分在 vector 中插入值并将其放在后面。我尝试使用 vector.back()-value 但它不允许我这样做。这是代码片段
tempVector.insert(inputs.back()-temp,inputs[loopVar]);
显示的错误是
no instance of overloaded function "std::vector<_Ty, _Alloc>::insert [with _Ty=int, _Alloc=std::allocator]" matches the argument list
我试着在网上找一些像这样的例子,但找不到太多。有人可以告诉我我在这里做错了什么吗?我是 STL 和 c++14 的新手
最佳答案
... insert values in a vector using a slice of other vector and put it at the back...
解决方案一:
有一个 std::vector::insert()
具有以下形式的重载:
template< class InputIt >
void insert( iterator pos, InputIt first, InputIt last);
所以你可以这样写:
std::vector<int> a = { 1, 2, 3, 4, 5 };
std::vector<int> b = { 6, 7, 8, 9, 10 };
b.insert(b.end(), a.begin() + 2, a.begin() + 5);
解决方案 2:
将std::copy
算法与std::back_insert_iterator
一起使用:
std::vector<int> a = { 1, 2, 3, 4, 5 };
std::vector<int> b = { 6, 7, 8, 9, 10 };
std::copy(a.begin() + 2, a.begin() + 5, std::back_inserter(b));
测试它:
for (auto& x : b)
std::cout << x << ' ';
将输出:6 7 8 9 10 3 4 5
关于c++ - 我们可以使用 back() 值索引对 vector 执行插入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47561222/