我有这个简单的代码:
std::vector<std::map<double,double>> v;
//populate v
//we know each map already has correct key order (enforced by c++)
//but i also want to make sure the different maps have correct key order
//this is how I do it using a pointer:
const double *last_key = nullptr;
for (const auto &map : v)
{
if (map.size() > 0) //ignore empty maps
{
if (last_key)
{
const auto &new_key = map.cbegin()->first;
if (!(*last_key < new_key))
throw std::runtime_error("invalid key order");
}
last_key = &(--map.cend())->first;
}
}
这对指针有好处吗?你会怎么做呢?
我知道的唯一真正的选择(如果我想避免指针)是这样做:
double last_key;
bool last_key_has_been_set = false;
这可行,但它要求 key 是默认可构造的,并且涉及不必要的 key 复制(与 double
不同的 key 类型的问题)。
最佳答案
好的,因为我现在(认为我)了解您的代码是关于什么的,所以这是我的看法:
auto iter = v.begin();
auto end = v.end();
while (iter != end && iter->empty())
++iter;
if (iter != end)
{
while (true) // loop and a half
{
auto next = iter+1; // at this point, we know iter != end
while (next != end && next->empty())
++next;
if (next == end)
break;
auto lhslast = lhs.end();
--lhslast;
if (lhslast->first > next->begin()->first)
throw std::runtime_error("invalid key order");
iter = next;
}
}
编辑:
上面的代码可以使用另一种算法进一步改进:
替换
while (iter != end && iter->empty())
++iter;
与
iter = std::find_if(iter, end,
[](std::map<double, double> const& m) { return m.empty(); });
和 next
循环类似。
另一种选择是注意,如果它不是空 map ,您可以只使用 adjacent_find
。因此,另一种选择是利用 Boost 的 filter_iterator
来去除空映射。这样做
#include <boost/iterator/filter_iterator.hpp>
struct is_not_empty
{
template<typename Container> bool operator()(Container const& c) const
{
return !c.empty();
}
};
然后在你的代码处
auto fbegin = boost::make_filter_iterator(is_not_empty(), v.begin(), v.end());
auto fend = boost::make_filter_iterator(is_not_empty(), v.end(), v.end());
if (std::adjacent_find(fbegin, fend,
[](std::map<double, double> const& lhs,
std::map<double, double> const& rhs) -> bool
{
auto lhslast = lhs.end();
--lhslast;
return lhslast->first > rhs.begin()->first;
}) != fend)
throw std::runtime_error("invalid key order");
过滤器迭代器确保只考虑非空映射。
关于c++ - 我应该避免在这里使用指针吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17379594/