ora*_*001 5 c++ performance sample vector subset
我正在寻找一种有效的方法来修剪或复制现有std :: vector的子集.符合子集/保留条件的元素的标准是它们的索引包含在单独的预定义std :: vector中.
e.g std::vector<String> Test = { "A", "B", "C", "D", "E"}
std::vector<int> SelectionV = {1,2,5}
Result = {"A", "B", "E"}
Run Code Online (Sandbox Code Playgroud)
我将在一个非常大的向量上执行此操作,并且可能定期执行此操作,因此我正在寻找尽可能有效的方法.
我也在考虑另一种选择,但又不确定一种有效的方法是......
当对象Test被填充时(在我的情况下它是第三方定义的对象),它是使用迭代器进行单次传递的结果(不能直接访问元素).我想知道是否可以只添加出现在SelectionV中定义的计数中的Test向量元素
例如
int count = 0
for (Iterator.begin, Iterator.end(), Iterator++) {
if (count is a number contained in selectionV)
add to Test
}
Run Code Online (Sandbox Code Playgroud)
但我认为这会导致每次迭代都会通过selectionV,这比简单地添加所有元素并稍后选择子集要低得多.
任何帮助非常感谢.
小智 7
您还可以使用标准库:
std::vector<std::string> Result(SelectionV.size(), 0);
std::transform(SelectionV.begin(), SelectionV.end(), Result.begin(), [Test](size_t pos) {return Test[pos];});
您可以通过增加顺序对 SelectionV 向量进行排序,然后您可以重写 for 循环,如下所示:
int index = 0, nextInSelectionV = 0;
for (Iterator.begin; nextInSelectionV < SelectionV.lengh() && Iterator.end(); Iterator++) {
if (index == SelectionV[nextInSelectionV]) {
add to Test
nextInSelectionV++;
}
index++;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3716 次 |
| 最近记录: |