내 프로젝트 중 하나에서 std::vector<double> values
의 특정 요소를 제거해야합니다. 제거해야하는 인덱스는 간격 벡터로 제공됩니다. 예를 들어, {1,3}
은 1에서 3까지의 인덱스를 values
에서 제거해야한다는 것을 의미합니다.std :: vector 범위의 벡터를 지우는 가장 좋은 방법
주어진 간격은 상호 배타적이라고 가정 할 수 있습니다.
아래 표시된 코드는 원하는 동작을 보여줍니다.
#include <iostream>
#include <vector>
int main(int argc, char** args) {
// Intervals of indices I have to remove from values
std::vector<std::pair<int, int>> intervals = { {1,3},{7,9},{13,13} };
// Vector of arbitrary values.
std::vector<double> values = {4.2,6.4,2.3,3.4,9.1,2.3,0.6,1.2,0.3,0.4,6.4,3.6,1.4,2.5,7.5 }
removeIntervals(values, intervals);
// intervals should contain 4.2,9.1,2.3,0.6,6.4,3.6,1.4,7.5
}
이 작업을 수행하는 데 필요한 최단 코드는 무엇입니까?
내 가장 좋은 방법은 지금까지입니다 :
void removeIntervals(std::vector<double>& values, const std::vector < std::pair<int, int>>& intervals) {
std::vector<bool> flags(values.size(), true);
std::vector<double> ret;
for (auto interval : intervals) {
std:fill(flags.begin() + interval.first, flags.begin()+interval.second+1, false);
}
for (auto i = 0; i < values.size(); i++) {
if (flags[i]) ret.push_back(values[i]);
}
values = ret;
}
내 간격이 겹치지 연속 것을, 가정 할 수있다. 그것은 뒤에서 앞으로 지우기를 수행하는 것으로 나타났다.
void removeIntervals2(std::vector<double>& values, const std::vector < std::pair<int, int>>& intervals) {
auto revIntervals = intervals;
std::reverse(revIntervals.begin(), revIntervals.end());
for (auto interval : revIntervals) {
values.erase(std::begin(values) + interval.first, std::begin(values) + interval.second + 1);
}
}
는'표준 : remove_if'를보십시오. 예제 시나리오에서 실제로는 – user463035818
이 아주 간단해야합니다. {1, 3} 및 {7,9}을 삭제하면 벡터에 8 개의 요소가 생기므로 {13,13}을 삭제할 수 없습니다. 어쩌면 문제 설명에 업데이트가 필요할까요? – incrediblehulk
@incrediblehulk 질문이 업데이트가 필요하다고 생각하지 않습니다. 당신이 묘사하는 것은 그것의 일부일뿐입니다. – user463035818