如何切片在c ++中的向量和分配给自己? [英] How to slice a vector in c++ and assign to itself?
问题描述
我想知道如何用一个向量的子集替换向量的内容,而不重新分配一个新的向量(我发现的每个问题似乎都有分配一个新向量的目的) p>
例如:
vector< int> * testVec = new vector< int> ; {1,2,3,4,5};
//对切片向量进行一些操作{2,3,4}而不重新分配
// testVec现在应该具有内容{2,3,4}
问题不清楚的使用范围, $ c> std :: vector :: erase 就足够了,不会产生任何重新分配。
std :: vector< int> testVec {1,2,3,4,5};
testVec.erase(testVec.begin()+ 4,testVec.end());
testVec.erase(testVec.begin(),testVec.begin()+ 1);
通过首先删除向量的尾部,可以确保值只被移动一次。 p>
注意,我假设你实际上不需要使用 std :: vector
的指针。
I would like to know how I can replace the contents of a vector with a subset of that vector, without re-allocating a new vector (every question I have found appears to have the purpose of allocating a new vector)
example:
vector<int>* testVec = new vector<int>{1, 2, 3, 4, 5};
//do some operation to slice vector, to say {2, 3, 4} without re-allocating
//testVec should now have contents {2, 3, 4}
The question is not clear on the usage scope, but two calls to std::vector::erase
would suffice and don't incur any reallocation.
For your example:
std::vector<int> testVec{1, 2, 3, 4, 5};
testVec.erase(testVec.begin() + 4, testVec.end());
testVec.erase(testVec.begin(), testVec.begin() + 1);
By first removing the tail of the vector you can make sure the values are only moved once.
Note that I assumed that you don't actually need to use a pointer to std::vector
.
这篇关于如何切片在c ++中的向量和分配给自己?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!