我有一个遗留代码简化如下:
std::map< int, std::vector<int> > list2D;
给定一个范围(例如 10 - 90 之间的数字范围)我需要先过滤 map 并消除不在数字范围内的元素。再次给出元素
20 -> {10,20}, 40 -> {500,200}, 100 -> {1,2,3} 假设范围是 10-90 我需要 100 的过滤器。
然后我需要连接所有剩下的 vector 。所以结果将是 {10,20,500,200} 。
我的遗留代码是用两个 for 循环来完成的。我打算使用 lower_bound 函数进行过滤步骤。但似乎我仍然需要一个 for 循环。简化版本可以在下面看到。老实说,带有 2 个 for 循环的版本看起来更简单。
void simplifiedFoo ()
{
std::vector<int> returnVal;
std::map<int, std::vector<int> > list2D = {{20 , {10,20} },
{40 , {500,200}},
{100 , {1, 2, 3}} };
auto itlow=list2D.lower_bound (10);
auto itup=list2D.lower_bound (50);
if ( itlow != list2D.end() && itup == list2D.end() )// Don't like this if even not sure if it is correct.
--itup;
while ( itlow != itup) // How to avoid second loop
{
returnVal.insert(returnVal.end(), itlow->second.begin(), itlow->second.end());
++itlow;
}
for ( auto elem : returnVal)
std::cout << elem << " " ;
return 0;
}
什么是更好的干净方式(我需要用 vs2010 实现它)?有没有干净的方法可以为我的案例在 C++ 中实现“减少”功能?
最佳答案
不确定这是否是您的意思,但如果您正在寻找使用“std oneliners”的方法,这会起作用:
std::for_each(itlow, itup,
[&returnVal](const auto& elem) {
returnVal.insert(returnVal.end(), elem.second.begin(), elem.second.end());
});
现在,我们可以称其为“最好的清洁方式”吗?我认为这是有争议的。
关于c++ - 将 vector 映射的选择性元素减少为 vector ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40724270/