I have a Visual Studio 2008 C++ project where I would like to copy one struct element of a vector of that struct type to a new vector. For example:
struct Foo {
int a;
long b;
};
std::vector< Foo > v1;
std::vector< long > v2;
for( std::vector< Foo >::const_iterator it = v1.begin(); it != v1.end(); ++it )
{
v2.push_back( it->b );
}
Is there a better/more elegant way than this?
Thanks,
PaulH
In Visual C++ 2008, no, this is about as “elegant” as it gets. The Standard Library provides algorithms that can be used to manipulate containers, but in most scenarios–especially in simple use cases like this one–they are far too cumbersome to use.
C++11 adds lambda expressions to C++. Visual C++ 2010 and recent versions of other C++ compilers support this C++11 feature. With lambda expressions, you can easily use the
transformalgorithm for your task:Without lambda expressions, you’d have to define a function to extract the
belement from the struct:You could then use this function with the
transformalgorithm:However, for simple use cases like this, this can quickly lead to unwieldy code as it is difficult to neatly keep all of the related functions together.