4

I have Example Class:

class Example {
private:
  int testValue1;
  int testValue2;
  int testValue3;

public:
  Example(int pVal1, int pVal2, int pVal3);

  Example(const Example);

  const Example operator =(const Example);

  inline int getValue1() { return testValue1; }

  inline int getValue2() { return testValue2; }

  inline int getValue3() { return testValue3; }

};

In source code I have std::vector of Example Objects.

Is it possible with some std::algorithm, std::numeric functions make a sum of Value1 of all Obejcts in vector

something like this: std::accumulate(vector.begin(), vector.end(), 0, SomeFunctorOrOthers)....

Of course I can use an iterators... but if it is possible ii want to know it

Thank you very much!


How to add JavaScript Code in WordPress Plugins?

Hello i have a problem in creating the WordPress plugins..
I need to include the <script>...</script> in my plugins, but it loaded above the tag.

<script>window.jQuery || document.write('<script src="http://mydomain/wp-content/plugins/myplugins/js/vendor/jquery-1.9.1.min.js"><\/script>')</script>

I need to load it before </body> tag in HTML.

I was try it using wp_register_script and wp_enqueue_script, but it the script load like this

<script type='text/javascript' src='http://mydomain/wp-content/plugins/myplugins/js/vendor/jquery-1.9.1.min.js?ver=3.6.1'></script>

So, how I load it between <script>...</script> code to make output like this

<script>window.jQuery || document.write('<script src="http://mydomain/wp-content/plugins/myplugins/js/vendor/jquery-1.9.1.min.js"><\/script>')</script>

Thank you...

4

3 回答 3

12

当然:

int sum = 
std::accumulate (begin(v), end(v), 0, 
    [](int i, const Object& o){ return o.getValue1() + i; });

请注意,由于Objectconst-ref 将其传递给 lambda,因此您需要制作 getter const(无论如何这是一个好习惯)。

如果你没有 C++11,你可以定义一个带有重载的仿函数operator()。我会更进一步,将其设为模板,以便您可以轻松决定要调用哪些 getter:

template<int (Object::* P)() const> // member function pointer parameter
struct adder {
    int operator()(int i, const Object& o) const
    {
        return (o.*P)() + i;
    }  
};

像这样将它传递给算法:adder<&Object::getValue2>()

于 2013-10-17T11:37:13.373 回答
3
std::accumulate(vector.begin(), vector.end(), 0, [](const int& a, Example& b)
{
return a + b.getValue1();
});
于 2013-10-17T11:37:44.717 回答
2
std::accumulate(v.begin(), v.end(), 0);

如果您重载运算符铸造就足够了int

class Example {
  ...

  operator int()  { return testValue1; }
};

缺点是,您可能不希望这种重载通常应用于您的班级。

于 2013-10-17T11:37:08.640 回答