2
 vector<double> result(vectorOfClassA.size());
 vector<classB> temp(vectorOfClassA.size());
 std::transform(vectorOfClassA.begin(), vectorOfClassA.end(), back_inserter(temp),
                std::tr1::bind(&A::memberVariableOfClassB, std::tr1::placeholders::_1));
 std::transform(temp.begin(), temp.end(), back_inserter(result),
                 std::tr1::bind(&B::getValue, std::tr1::placeholders::_1));

I like to use one transform but it can't compile

std::transform(vectorOfClassA.begin(), vectorOfClassA.end(), back_inserter(result),
               std::tr1::bind(&B::getValue,
                              std::tr1::bind(&A::memberVariableOfClassB,
                                             std::tr1::placeholders::_1)));

Here double getValue() is class B member function. How to do it or what is wrong with my code?

  • 1
    Could the reason for the failed compile simply be that you misspelled `memberVariableOfClassB`? – Rob Kennedy Oct 19 '12 at 14:24
  • There is little chance because I copy and paste it – user1759558 Oct 19 '12 at 15:02
  • Then how do you explain that your "failed" code says `memberVariableOfCallB`? *Call* is not the same as *Class*. – Rob Kennedy Oct 19 '12 at 15:29
  • memberVariableOfCallB here should be type of classB member Variable, not classB, am I right? – user1759558 Oct 19 '12 at 16:09
  • Your first code block says `memberVariableOfClassB`, but the second code block says `memberVariableOfCallB`. Do you see the difference? Do you understand why that difference is important? I can't tell you what it's supposed to be since I can't see the rest of your code. It's *your* code, so you should already know what the name of your own variable or function is. – Rob Kennedy Oct 19 '12 at 17:51
  • It is my fault. It is memberVariableOfClassB. My code use concrete class name. Thanks anyway. – user1759558 Oct 19 '12 at 17:58

1 Answers1

2

If your compiler supports C++11, you can make use of a lambda:

std::transform(vectorOfClassA.begin(), vectorOfClassA.end(), 
  back_inserter(result),
  [] (const A& a)
  {
  return a.memberVariableOfClassB.GetValue();
  });
Andriy
  • 8,486
  • 3
  • 27
  • 51
  • 2
    If your compiler is old, you could use a regular function instead of a lambda function (same idea) – Kos Oct 19 '12 at 14:21
  • @user1759558: It is a capture clause of a lambda expression. [What is a lambda expression in C++11?](http://stackoverflow.com/questions/7627098/what-is-a-lambda-expression-in-c11) – Andriy Oct 19 '12 at 14:40