我有这个简单的代码:
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;
这可行,但它要求密钥是默认可构造的,并且涉及不必要的密钥复制(与 不同的密钥类型的问题double
)。