gpt4 book ai didi

c++ - 有没有办法从 map::find() 获得 boost::optional 结果?

转载 作者:行者123 更新时间:2023-11-30 05:00:35 26 4
gpt4 key购买 nike

给定一个 std::map<,> m ,我能做到:

const auto iterator = m.find(k);
if (iterator != m.end())
{
const auto& value = iterator->second;
// ...
}

我想做同样的事情,但使用 boost::optional .像这样的东西:

const auto o = boost::find_optional(m, k);
if (o)
{
const auto& value = o.get();
// ...
}

已经有类似的东西了吗?

最佳答案

解决了我在其他答案中注意到的一些限制的版本:

namespace stl { 

namespace map {

namespace detail {
template <typename K, typename Map>
static auto lookup(K const &key, Map &&map) -> boost::optional<decltype(map.at(key)) &> {
auto it = map.find(key);
if (it != map.end())
return it->second;
return boost::none;
}
} // namespace detail

template <typename K, typename Map>
static decltype(auto) lookup(K const &key, Map &&map) {
return detail::lookup(key, std::forward<Map>(map));
}

template <typename K, typename Map>
static decltype(auto) lookup(boost::optional<K> const &key, Map &&map) {
return key ? (lookup)(*key, std::forward<Map>(map)) : boost::none;
}

}

using map::lookup;
//using set::lookup; // extended ideas
//using map::contains;
//using set::contains;
}

用一个测试程序来演示一下:

Live On Coliru

#include <iostream>
#include <boost/optional/optional_io.hpp>

using stl::lookup;

template <typename Map>
void traverse(char const* startkey, Map const& m) {
std::cout << "\nTraverse from " << startkey << ":\n";
auto cursor = lookup(startkey, m);

do std::cout << "Lookup result: " << cursor << "\n";
while (cursor = lookup(cursor, m));
}

int main() {

std::map<std::string, std::string> m {
{ "Hello", "World" },
{ "World", "Peace" },
{ "Peace", "Troops" },
};

traverse("Hello", m);

// mutation:
if (auto peace = lookup("Peace", m))
*peace = "Love";

traverse("Hello", m);
}

打印

Traverse from Hello:
Lookup result: World
Lookup result: Peace
Lookup result: Troops

Traverse from Hello:
Lookup result: World
Lookup result: Peace
Lookup result: Love

关于c++ - 有没有办法从 map::find() 获得 boost::optional 结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50690792/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com