小编Ada*_*adi的帖子

有没有办法轻松处理返回std :: pairs的函数?

C++ 11具有std::minmax_element返回一对值的函数.然而,这对于处理和读取来说是相当混乱的,并且产生一个额外的,后来无用的变量来污染范围.

auto lhsMinmax = std::minmax_element(lhs.begin(), lhs.end());
int &lhsMin = *(lhsMinMax.first);
int &lhsMax = *(lhsMinmax.second);
Run Code Online (Sandbox Code Playgroud)

有一个更好的方法吗?就像是:

int lhsMin;
int lhsMax;
std::make_pair<int&, int&>(lhsMin, lhsMax).swap(
    std::minmax_element(lhs.begin(), lhs.end()));
Run Code Online (Sandbox Code Playgroud)

c++ tuples minmax c++11 std-pair

33
推荐指数
3
解决办法
2171
查看次数

如果硬碰撞错误不太可能,我应该使用吗?

我经常发现自己编写的代码看起来像这样:

if(a == nullptr) throw std::runtime_error("error at " __FILE__ ":" S__LINE__);
Run Code Online (Sandbox Code Playgroud)

我应该更喜欢处理错误if unlikely吗?

if unlikely(a == nullptr) throw std::runtime_error("error at " __FILE__ ":" S__LINE__);
Run Code Online (Sandbox Code Playgroud)

编译器会自动推断出应该缓存代码的哪一部分,或者这实际上是否有用?为什么我看不到很多人处理这样的错误?

c++ gcc c++17 likely-unlikely

16
推荐指数
3
解决办法
2633
查看次数

是否可以在jupyter中重定向单元格输出

我正在使用jupyter和jupyter-nbconvert来创建一个html演示文稿.但是,我有一些单元格生成一个输出图像,我想在另一张幻灯片上共享.是否可以将一个单元格的输出重定向到自己的幻灯片?

python ipython-notebook reveal.js jupyter jupyter-notebook

13
推荐指数
1
解决办法
681
查看次数

如何进行常量校正?

我有一个const-correctness问题,我似乎无法解决.这是我的程序的结构:

class Node
{
    private:
        int            id;
        std::set<Node*> neighbours;
    public:
        Node();
        Node(int id_p);

        void set_id(const int& id_p);
        int  get_id() const;
        void add_neighbour(Node* neighbour);
        bool is_neighbour(Node* neighbour) const;

        friend bool operator <(const Node& lhs, const Node& rhs);
};

class Graph
{
    private:
        std::set<Node> node_list;
    public:
        Graph();

        void        add_node(int id);
        const Node* get_node_by_id(int id) const;
        bool        has_node(int id) const;
        void        check_add_node(int id);
        void        add_edge(int id_1, int id_2);
        bool        has_edge(int id_1, int id_2) const;
        void        check_add_edge(int id_1, int id_2);

        (...)
};
Run Code Online (Sandbox Code Playgroud)

现在问题是,如果我调用该函数Graph::get_node_by_id() …

c++ const const-correctness stdset

9
推荐指数
1
解决办法
291
查看次数

编译时消息测试constexpr

当对编译时 constexpr 的测试评估为真时,是否可以打印消息?像 static_assert 这样的东西而不停止编译器。

constexpr Application::Mode SETUP_MODE = Application::Debug;

// Can I somehow test if the SETUP_MODE is debug for pragma message?
#pragma message("Application mode is set to Debug!")

static_assert(SETUP_MODE != Application::Debug, 
    "Application mode is set to Debug!"); // Can I somehow just print this message without aborting the compilation?
Run Code Online (Sandbox Code Playgroud)

c++ static-assert constexpr c++14

5
推荐指数
0
解决办法
598
查看次数

为什么没有通过“”比较检查空字符串的优化?

Quick Bench上检查的这个 google-benchmark 代码表明,它的string::empty()运行速度比与空字符串文字相比要快得多。但是,创建一个名称字符串""实际上会使编译器优化检查:

bool compareWithNamedConst(const std::string& target) {
    const std::string emptyString = "";
    return emptyString == target;
}

bool compareWithLiteral(const std::string& target) {
    return "" == target;
}

bool compareWithRvalue(const std::string& target) {
    return std::string{""} == target;
}

bool checkForEmpty(const std::string& target) {
    return target.empty();
}
Run Code Online (Sandbox Code Playgroud)

每个调用的性能如下所示:

正如您所看到的,与""所有其他选项相比,比较速度非常慢。我想知道为什么会这样?它必须以某种方式与未应用 SSO 相关const char*,作为测试:

bool compareWithLiteral(const std::string& target) {
    return "test with a longer string not optimized" == target;
}

bool compareWithRvalue(const …
Run Code Online (Sandbox Code Playgroud)

c++ gcc clang c++14

5
推荐指数
1
解决办法
192
查看次数

函数返回其参数或检查nullptr

我想循环一个向量并过滤掉所有非空指针元素.我正在寻找一个std检查nullptr的std函数或一个实际返回传递给它的函数的函数(比如std::forward),因为空指针会求值false.

std::copy_if(dynamicObjects.begin(), dynamicObjects.end(),
    std::back_inserter(existingObjects), 
    std::is_pointer<ObjectType*>); // This does not compile

std::copy_if(dynamicObjects.begin(), dynamicObjects.end(),
    std::back_inserter(existingObjects), 
    std::forward<ObjectType*>); // This does not compile either

std::copy_if(dynamicObjects.begin(), dynamicObjects.end(),
    std::back_inserter(existingObjects), 
    static_cast<bool>); // This won't help me :)

std::copy_if(dynamicObjects.begin(), dynamicObjects.end(),
    std::back_inserter(existingObjects), 
    [] (const auto a) { return a; } ); // This is awkward
Run Code Online (Sandbox Code Playgroud)

c++ c++11 c++14 c++17

3
推荐指数
1
解决办法
146
查看次数

按地址访问std :: array数据是否安全?

我想在std :: array对象上使用按位数据转换,为此,我需要知道存储数组地址是否安全,或者是否存在更改数据位置的函数.例如:

std::array<int, 100> array;
int* startMarker = array.data();
(filing the array and doing operations on it)
std::cout << *startMarker << std::endl;
Run Code Online (Sandbox Code Playgroud)

谢谢你的回答.

c++ arrays dereference stdarray

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

我可以使用匿名lambdas来保持静态值吗?

我想创建一个我想要超出范围的对象,但是设置对其字段的引用.这种做法有什么好处吗?

A* a;
B* b;
[a, b]
{
   static Loader loader("some", "argument", "the constructor", "takes");
   a = loader.getA();
   b = loader.getB();
}();
Run Code Online (Sandbox Code Playgroud)

匿名lambda是否以其拥有的价值被摧毁?是否有更好的设计模式来实现同样的目标?

好吧,这似乎是一个很好的方法.我的问题仍然是,如果匿名lambda在解析时被破坏(并且使用它拥有的静态变量).

c++ lambda singleton static c++17

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

使用glew和SDL2

当我想一起使用SDL2和glew时,我得到以下错误glewInit():

缺少GL版本

重现错误的示例:

#include <iostream>

#define NO_SDL_GLEXT
#include <GL/glew.h>
#include "SDL2/SDL.h"
#include "SDL/SDL_opengl.h"

int main(int argc, char **argv)
{
    if(SDL_Init(SDL_INIT_VIDEO) < 0)
    {
        std::cout << "SDL could not initialize! SDL Error: " << SDL_GetError() << std::endl;
        return -1;
    }
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MAJOR_VERSION, 3); // Does nothing
    SDL_GL_SetAttribute(SDL_GL_CONTEXT_MINOR_VERSION, 3); // Does nothing
    SDL_Window *window = SDL_CreateWindow("Example for SO", SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, 800, 600, SDL_WINDOW_OPENGL);
    if(window == nullptr)
    {
        std::cout << "Window could not be created! SDL Error: " << SDL_GetError() << std::endl; …
Run Code Online (Sandbox Code Playgroud)

c++ opengl glew sdl-2

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

C++是否具有移动和删除语义?

是否有可能在C++中创建一次性变量而没有任何带有括号的时髦业务?

这是我想要实现的一个例子:

const float _phiTemp  = atan2(tan(cluster.beta), tan(cluster.alpha));
const float phi       = HALF_PI - std::abs(HALF_PI - std::abs(_phiTemp));
// After running this code I want _phiTemp to be unaccessible, and the
// compiler to send an error if I ever try
Run Code Online (Sandbox Code Playgroud)

这是我想要的漫长而丑陋的实现:

const float phi = 0;
{
     const float _phiTemp  = atan2(tan(cluster.beta), tan(cluster.alpha));
     float& phiRef = const_cast<float&> phi;
     phiRef = HALF_PI - std::abs(HALF_PI - std::abs(std::move(_phiTemp)));
}
// _phiTemp is disposed and phi is a const, and safely used in the …
Run Code Online (Sandbox Code Playgroud)

c++ scope lifetime delete-operator move-semantics

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