相关疑难解决方法(0)

std::abs 与 std::transform 不起作用

拿这个例子:

#include <vector>
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <cmath>

void PrintVec(const std::vector<float>&);
int main(int argc, char * argv[]){

float vals[] = {-1.2,0.0,1.2};
std::vector<float> test(vals, vals + sizeof(vals) / sizeof(float));
std::vector<float> absTest(3);

std::transform(test.begin(), test.end(), absTest.begin(), std::abs<float>());

PrintVec(test);
PrintVec(absTest);

return 0;
}

void PrintVec(const std::vector<float> &vec){
for (unsigned int i = 0; i < vec.size(); ++i){
    std::cout << vec[i] << '\n';
}
return;
}
Run Code Online (Sandbox Code Playgroud)

使用 gcc 4.3.4 和 VS 2013 我得到编译器错误。对于 gcc 来说:

testTransformAbs.cpp:15: 错误:'float' 之前的预期主表达式

对于 VS 2013,其:

错误 …

c++ stl

4
推荐指数
2
解决办法
2359
查看次数

使用成员变量作为谓词

我试图在一个对象的向量中找到一个对象,其中一个成员变量的值为true.可以在没有定义lamba函数或函数对象的情况下完成,只需指定成员变量本身:

class A
{
public:

   explicit A(bool v, int v2, float v3) : value(v), value2(v2), value3(v3)
   {}
   ...
   bool value;
   int value2;
   float value2;
   ...
}

int main()
{
    std::vector<A> v;
    v.push_back(A(false, 1, 1.0));
    v.push_back(A(true, 2, 2.0));
    v.push_back(A(false, 3, 3.0));

    auto iter = std::find_if(v.begin(), v.end(), &A::value);
}
Run Code Online (Sandbox Code Playgroud)

如上所述编译不起作用,因为它假设A*而不是A.

使用lambdas并不是一个问题,只是好奇.

c++

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

编写自由函数来获取类成员的最小方法是什么?

(读完这篇文章及其接受的答案后,这个问题突然出现在我的脑海中。)

假设一个Foo您无法修改的类,它有一个publicmember bar,但没有它的 getter 。

您可能想要编写一个函数来在传递 a 时获取该成员Foo,以便您可以在更高阶的函数中使用它,例如std::transform和 类似的函数。

换句话说,给定这样一个类

struct Foo {
    int bar{};
    ~Foo() { bar = -1; } // on most compilers this helps "verifying" that the object is dead
};
Run Code Online (Sandbox Code Playgroud)

我想要一些getFoo与具有相同语义的类型,其中是 类型的任何对象,可以是纯右值、x值或左值。getBar(expr-of-type-Foo)expr-of-type-Foo.barexpr-of-type-FooFoo

你怎么写呢?

我最初想到的是:

        constexpr auto getBar = overload(
            [](auto& foo) -> decltype(auto) { return (foo.bar); },
            [](auto const& foo) -> decltype(auto) { return …
Run Code Online (Sandbox Code Playgroud)

c++ generics getter non-member-functions perfect-forwarding

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