Reputation: 6149
I have a struct:
struct myStruct {
// there are other members as well
float U, V, W;
}
std::vector <myStruct> myVec;
myVec.resize(num);
I want to pass only myVec[].U for all myVec's to a function.
Upvotes: 0
Views: 754
Reputation: 12170
Judging by your code example and your explanation, you want something like this:
#include <iostream>
#include <vector>
using namespace std;
struct myStruct {
float u;
};
void foo(float& f) {
f = 44.1;
}
int main() {
vector<myStruct> myVec(5, myStruct());
for (auto& i : myVec) {
foo(i.u);
}
for (const auto& i : myVec) {
cout << i.u << endl;
}
}
// g++ -Wall -Wextra test.cc -o test -O3 -s -std=c++0x
for example.
As in, all you wanted to know how to do is how to pass myVec[n].U to a function.
But, looking at your comments and other posts, I'm not sure.
Upvotes: 0
Reputation: 279305
Pass a pair of iterators to the function:
struct pick_U : std::unary_function<myStruct&, float&> {
float &operator()(myStruct &ms) const { return ms.U; }
};
your_function(
boost::make_transform_iterator(myVec.begin(), pick_U()),
boost::make_transform_iterator(myVec.end(), pick_U()),
... other args ...
};
Then your_function
can iterate over the floats.
Upvotes: 5
Reputation:
Two options:
First option: Redesign so that instead of
struct myStruct
{
// there are other members as well
float U, V, W;
}
std::vector <myStruct> myVec;
You have
struct myStructs {
// there are other members as well
std::vector<float> Us, Vs, Ws;
}
myStructs allOfMyStructs;
Then you can simply pass the Us vector. (This is also known as data oriented programming)
Second option: copy all of the U elements into one vector.
std::vector<float> Us;
for (auto iter = myVec.begin(); iter != myVec.end(); iter++)
Us.push_back(iter->U);
Then you simply pass the Us vector.
Upvotes: 1
Reputation: 477248
Since an array of floats requires contiguous storage, and your vector myVec
does not store the U
s contiguously, you need to make a copy:
std::vector<float> uv;
uv.reserve(myVec.size());
for (auto const & s : myVec) { uv.push_back(s.U); }
// now use uv.data() if your callee needs a float*
On older compilers you have to say:
for (std::vector<myStruct>::const_iterator it = myVec.begin(), end = myVec.end(); it != end; ++it)
uv.push_back(it->U);
You may also have to say &uv[0]
instead of uv.data()
to get a raw pointer to the array.
Upvotes: 2