c++ - 我应该避免在这里使用指针吗?

标签 c++ dictionary pointers std stdmap

我有这个简单的代码:

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/

相关文章:

c++ - 为什么捕获变量会使 lambda 的类型唯一?

c++ - 在 Linux 上用 C++ 从文件打开进程

java - 从 Bloch 的 Effective Java in C++ (VS2010) 实现类型安全的异构容器

c++ - 为什么指针声明中需要数据类型?

C——指针三维数组

c++ - BerkeleyDB 并发

javascript - mapbox.js 上的自动完成输入

python - Django:获取查询集/字典中项目的固定值

python - 根据键 ckeys 之一的值对字典值进行排序

一个简短的例子没有分配被释放的c++指针