如何将2个列CSV文件读取到带有范围的地图中?
我给了一个CSV文件,每行两个元素:
1,2
12,40
11,7
...
我想将其阅读到 std :: map&lt< int,int>
中。
我该怎么做,使用 ranges library 和 range-v3 ?
是我得到的(在这个答案)
#include <boost/hof/lift.hpp>
#include <iostream>
#include <range/v3/istream_range.hpp>
#include <range/v3/range/conversion.hpp>
#include <range/v3/view/istream.hpp>
#include <range/v3/view/join.hpp>
#include <range/v3/view/chunk.hpp>
#include <range/v3/view/transform.hpp>
#include <range/v3/view/split.hpp>
#include <string>
using ranges::istream;
using ranges::to;
using namespace ranges::views;
constexpr auto splitAtComma = [](auto const& r) { return r | split(','); };
constexpr auto rngToString = [](auto const& r) { return r | to<std::string>; };
constexpr auto strToInt = BOOST_HOF_LIFT(std::stoi);
constexpr auto parseCoords = transform(splitAtComma)
| join
| transform(rngToString)
| transform(strToInt)
| chunk(2);
int main() {
auto lines = istream<std::string>(std::cin);
auto coords = lines | parseCoords;
std::cout << coords << std::endl;
}
目前,这
./main <<END
1,2
12,40
11,7
END
:输出
[[1,2],[12,40],[11,7]]
要点是,现在我不知道如何将该范围转换为地图。另外,我感觉自己在一条死胡同,因为 std :: map&lt&lt; int,int&gt;
的每个元素来自2 int
s ,但是在上面的范围 [1,2]
, [12,40]
和 [11,7]
是只是 int
s的范围,而不是在compile tiime上编码2 int
s。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
无需在此处使用
加入
,因为r | split(',')
已经为您提供了带有两个元素的范围。优先std :: From_chars
而不是std :: Stoi
。您只能使用标准库的
&lt; ranges&gt;
demo
注意
std :: move(r)
inviews :: transform
是必要的,因为我们需要构造oning_view
以避免悬而未决的问题。There is no need to use
join
here becauser | split(',')
already gives you a range with two elements. Preferstd::from_chars
overstd::stoi
.You can do this only using the standard library's
<ranges>
Demo
Note that the
std::move(r)
inviews::transform
is necessary because we need to construct anowning_view
to avoid the dangling issue.