简体   繁体   中英

pass only a member of std::vector's of struct to function (C++)

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.

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.

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM