#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void push_back(int v, vector<int>& coll)
{
coll.push_back(v);
}
int main()
{
int a[] = {1, 2, 3, 4, 5};
std::vector<int> b;
for_each(a, a + 5, bind2nd(ptr_fun(push_back), b));
}
the compiler said:
/usr/include/c++/4.1.2/bits/stl_function.h: In instantiation of ‘std::binder2nd<std::pointer_to_binary_function<int, std::vector<int, std::allocator<int> >&, void> >’:
tt5.cpp:15: instantiated from here
/usr/include/c++/4.1.2/bits/stl_function.h:435: error: forming reference to reference type ‘std::vector<int, std::allocator<int> >&’
/usr/include/c++/4.1.2/bits/stl_function.h: In function ‘std::binder2nd<_Operation> std::bind2nd(const _Operation&, const _Tp&) [with _Operation = std::pointer_to_binary_function<int, std::vector<int, std::allocator<int> >&, void>, _Tp = std::vector<int, std::allocator<int> >]’:
tt5.cpp:15: instantiated from here
/usr/include/c++/4.1.2/bits/stl_function.h:455: error: no matching function for call to ‘std::binder2nd<std::pointer_to_binary_function<int, std::vector<int, std::allocator<int> >&, void> >::binder2nd(const std::pointer_to_binary_function<int, std::vector<int, std::allocator<int> >&, void>&, std::vector<int, std::allocator<int> >&)’
/usr/include/c++/4.1.2/bits/stl_function.h:429: note: candidates are: std::binder2nd<std::pointer_to_binary_function<int, std::vector<int, std::allocator<int> >&, void> >::binder2nd(const std::binder2nd<std::pointer_to_binary_function<int, std::vector<int, std::allocator<int> >&, void> >&)
Your program is perfectly fine, except that you’re using
using namespace std;which you should be avoiding. In this case, that is possibly causing the problem.So I suggest you to remove
using namespace std;line, and try using fully-qualified names such asstd::vectorandstd::for_eachetc.Another fix could be this : just don’t use
std::for_each, as you don’t need it.Write this:
Done!
Now if you want to insert more items later on, then do this:
Hope that helps.
Your real scenario:
As you said in the comment:
If that is the case, then you should
std::transform.Suppose the source is
std::vector<person>and you want to pickagemember data from each element of this source collection, and insert them intobwhich isvector<int>:where
select_ageis defined as:If you can use C++11’s lambda, then it is much easier: