如何复制除一个特定元素之外的向量
How to copy a vector except one specific element?
我有一个带有一些值的向量。如何将其复制到另一个向量,以便复制除特定值(位于位置 x
- 当然x
将是一个参数)之外的所有值?
此外,我想将位置x
的值用于其他用途,因此我希望它将被保存。
有没有简单的方法可以做到这一点?
如何复制除一个特定值之外的 stl 向量?
您可以使用std::copy_if
:
std::vector<T> v = ....;
std::vector<T> out;
T x = someValue;
std::copy_if(v.begin(), v.end(), std::back_inserter(out),
[x](const T& t) { return t != x; });
如果没有 C++11 支持,则可以使用 std::remove_copy_if
并相应地调整谓词的逻辑。
如果您有 C++11,请使用 std::copy_if
,否则:
void foo(int n) {
std::vector<int> in;
std::vector<int> out;
std::copy(in.begin(), in.begin() + n, out.end());
std::copy(in.begin() + n + 1, in.end(), out.end());
}
这是有效的std::vector
因为它具有随机访问迭代器。
正如Luchian建议的那样,你应该使用erase()
#include <vector>
#include <iostream>
#include<algorithm>
int main(){
std::vector<int> vec1;
vec1.push_back(3);
vec1.push_back(4); // X in your question
vec1.push_back(5);
std::vector<int> new_vec;
new_vec = vec1;
new_vec.erase(std::find(new_vec.begin(),new_vec.end(),4));
for (unsigned int i(0); i < new_vec.size(); ++i)
std::cout << new_vec[i] << std::endl;
return 0;
}
对于您的第二个问题,确定向量中元素的索引
// determine the index of 4 ( in your case X)
std::vector<int>::iterator it;
it = find(vec1.begin(), vec1.end(), 4);
std::cout << "position of 4: " << distance(vec1.begin(),it) << std::endl;
相关文章:
- 向量元素的引用地址与它所指向的向量元素的地址不同.为什么
- C++:如何循环通过向量中的整数元素
- 如何在C++向量中奇数元素前面加上值-1,我在使用insert函数时遇到了问题
- 不允许在向量中添加更多元素
- 基于范围的 for 循环:迭代使用一个元素扩展的向量
- 使用并行参数向量调用元素向量的成员函数
- C++ 查找字符串中存在的元素向量
- 包含 std::threads 的元素向量
- 避免从单一元素向量转换为基元类型
- 对自定义元素向量进行排序时出现意外(至少对我来说)行为
- 如何为对元素(向量和int)配对创建unique_ptr也是unique_ptr
- 元素向量乘法 C++(代码不起作用)
- 时间和空间复杂性在二叉树的每个级别创建元素向量(NON-BST)
- 遍历结构元素向量
- 犰狳C++中的元素向量或矩阵乘法
- 为什么'std::vector<int> b{2};'创建 1 元素向量,而不是 2 元素向量?
- 可移动元素向量的大小调整是否有效?
- 唯一元素向量的c++模板函数
- 获取索引和元素-向量问题
- 定义一个生成元素向量的函数时,正确的方法是什么?