小编Ste*_*uer的帖子

在 STL 关联容器中使用基于迭代器的搜索和使用是否更快?

假设我正在尝试检查关联容器中是否存在某个项目,如果存在则对其进行处理。这样做的简单方法如下:

std::unordered_map<std::string, Whatever> thisIsAMap;

// C++17
if (thisIsAMap.count("key") > 0u) { doThing(thisIsAMap["key"]); }
// C++20
if (thisIsAMap.contains("key")) { doThing(thisIsAMap["key"]); }
Run Code Online (Sandbox Code Playgroud)

然而,这对我来说似乎总是有些浪费,因为它涉及两次查找相同的项目,这可能是一项非常昂贵的操作。相反,我倾向于这样做:

auto found = thisIsAMap.find("key");
if (found != thisIsAMap.end()) { doThing(found->second); }
Run Code Online (Sandbox Code Playgroud)

这只需要找到该项目一次,然后使用它。

后一种方法实际上更好吗?使用任何一种方法而不是另一种方法有什么好的理由吗?

c++ c++17 c++20

6
推荐指数
1
解决办法
117
查看次数

为什么 Visual Studio 在没有优化的情况下可以正确编译此函数,但在优化时却编译错误?

我正在做一些类似 y 组合器的 lambda 包装的实验(尽管我知道它们实际上并不是严格意义上的 y 组合器),但我遇到了一个非常奇怪的问题。我的代码在调试配置中完全按照我的预期运行(关闭优化),但跳过了发布中的大(而且很重要!)位(设置为Optimizations (Favor Speed) (/Ox))。

请注意,lambda 函数的内部基本上无关紧要,它们只是为了确保它可以正确递归等。

// main.cpp
#include <iostream>
#include <string>
#define uint unsigned int

// Defines a y-combinator-style thing to do recursive things. Includes a system where the lambda can declare itself to be obsolete.
// Yes, it's hacky and ugly. Don't worry about it, this is all just testing functionality.
template <class F>
class YCombinator {
public:
    F m_f; // the lambda will be stored here
    bool m_selfDestructing = …
Run Code Online (Sandbox Code Playgroud)

c++ lambda y-combinator visual-studio c++20

5
推荐指数
2
解决办法
141
查看次数

如何管理需要从递归函子/lambda 派生的模板参数的声明?

我正在尝试构建一个具有递归能力的 lambda 自作用域的干净整洁的实现(这基本上是一个 Y 组合器,尽管我认为技术上不完全)。这是一个旅程,它带我到许多其他人中,这个线程这个线程这个线程

我已经尽可能干净地归结了我的问题之一:如何传递以 lambda 作为模板参数的模板化函子?

#include <string>
#include <iostream>
#define uint unsigned int

template <class F>
class Functor {
public:
    F m_f;

    template <class... Args>
    decltype(auto) operator()(Args&&... args) {
        return m_f(*this, std::forward<Args>(args)...);
    }
};
template <class F> Functor(F)->Functor<F>;

class B {
private:
    uint m_val;
public:
    B(uint val) : m_val(val) {}
    uint evaluate(Functor<decltype([](auto & self, uint val)->uint {})> func) const {
        return func(m_val);
    }
};

int main() {
    B b = B(5u); …
Run Code Online (Sandbox Code Playgroud)

c++ lambda y-combinator c++17

2
推荐指数
1
解决办法
67
查看次数

标签 统计

c++ ×3

c++17 ×2

c++20 ×2

lambda ×2

y-combinator ×2

visual-studio ×1