【发布时间】:2015-03-19 19:08:56
【问题描述】:
我想提取一个填充了结构的向量的子集,并形成一个新的向量,其中只填充了该子集的一个成员变量。
主向量填充了这样的结构:
struct ImageParams{
double startTime;
double stopTime;
std::string path;
std::string activeInstrument;
bool projected;
};
假设我的应用程序已从 t0 -> t1 跳转,那么我希望每个 startTime 在 t0 和 t1 之间。我目前使用二进制查找操作遍历主向量,并将每个 startTime 存储在一个新的返回向量中,如下所示:
captureTime = t1;
while (captureTime > t0){
auto binary_find = [](std::vector<ImageParams>::iterator begin,
std::vector<ImageParams>::iterator end,
const ImageParams &val,
bool(*cmp)(const ImageParams &a, const ImageParams &b))->std::vector<ImageParams>::iterator{
std::vector<ImageParams>::iterator it = std::lower_bound(begin, end, val, cmp);
if (it != begin){
return std::prev(it);
}
return end;
};
// Finds the lower bound in at most log(last - first) + 1 comparisons
auto it = binary_find(mainVec.begin(), mainVec.end(),
{ captureTime, 0, "", "", false }, cmp);
if (it == mainVec.end()) return false;
if (it->startTime < t0) break;
returnVec.push_back(it->startTime);
captureTime = it->startTime - 1;
}
我想要实现的目标:
这行得通,但我认为 while 循环看起来很难看。我在想也许有一种有效的方法(假设一个在 mainVec 中找到两个匹配时间 t0 和 t1 的迭代位置)来形成一个只有 startTime 成员变量的新向量。
我想像这样,
std::vector<double> returnVec = std::vector(mainVec.begin () + first,
mainVec.begin () + last);
但可以说“只提取startTime 成员变量”
也许是我想多了?
【问题讨论】:
标签: c++ vector struct stl subset