Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c++ - Is there any possible way to get origin value using transformed iterator?

C++20 introduces the views::elements, views::keys and views::values to easily deal with range of tuple-like values:

std::vector v{std::tuple{'A', 1}, {'B', 2}, {'C', 3}};
auto it = std::ranges::find(v | std::views::elements<0>, 'B');
assert(*it == 'B');

After applying the adaptor, v | std::views::elements<0> become a range of the first element of each tuple, so the return type of the ranges::find is the iterator type of that transformed range.

But is there a possible way to transform it back to the origin iterator type to get the origin tuple?

assert(*magic_revert(it) == std::tuple{'B', 2});
question from:https://stackoverflow.com/questions/65912645/is-there-any-possible-way-to-get-origin-value-using-transformed-iterator

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's possible to get an iterator to the underlying range by calling .base().

assert(*it.base() == std::tuple{'B', 2});

But it might be more idiomatic to use a projection with std::ranges::find.

std::vector v{std::tuple{'A', 1}, {'B', 2}, {'C', 3}};
auto it = std::ranges::find(v, 'B', [](auto& e) { return std::get<0>(e); });
assert(*it == std::tuple{'B', 2});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...