simultaneously assign value to struct members

Hi,

If I have a struct of some vector members, like
1
2
3
4
5
6
7
struct {
vector<double> a;
vector<double> b;
vector<double> c;
// ...... continue

} struct_test

How can I assign a value (push_back()) to all the vector members simultaneously, instead of do it one by one?

Thanks in advance!
closed account (zb0S216C)
Threads, but that would be wasteful.

Wazzak
Oh? Is this the only way?
Framework was being overly literal. The only way to do any two things simultaneously is with threads. But I'm sure you weren't talking about being truly simultaneous.

If you use an array rather than different named items, you can push_back all of them in a loop:

1
2
3
4
vector<double> group[3];

for(int i = 0; i < 3; ++i)
  group[i].push_back( whatever );  // pushes a value into all vectors 


Although... you probably should not try to keep multiple vectors in sync. It might be best to combine the data into a struct, then have a vector of that struct:

1
2
3
4
5
6
7
8
9
10
11
struct Foo
{
  double a;
  double b;
  double c;
};


vector<Foo> foo;

foo.push_back( whatever );  // pushes 3 values (in one struct) 



There are other ways, but these are the two simplest.
Thanks for your reply. Based on this, I would like to ask a question a bit more complicated. If I have several array with same number of elements, like
1
2
3
double a[10] = {1.0, 2.0, // assign values...}
double b[10] = {1.1, 2.1, // assign values...}
// other similar arrays... 

I want to store them in a big object, with corresponding relationship E[0] = {a[0], b[0], ...}; E[1] = {a[1], b[1], ...}; E[2] = {a[2], b[2], ...}; ... like an Excel data table. Then I can sort the order of E[0], E[1], E[2], ... according to the value of a, or the value of b, or other elements.

How can I do this? Could someone please explain?



Last edited on
I think there is no native and easy way to do that.

I think there are two ways:
1. Search for an libary which includes a function which implements the algorithm (Maybe #include <algorithm> ? )
2. Implement it yourself
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>
#include <functional>
#include <vector>
 
struct A
{
    std::vector<int> a;
    std::vector<int> b;
    std::vector<int> c;
    A()
    {
        std::vector<std::reference_wrapper<std::vector<int>>> rv = { a, b, c };
        for ( auto x : rv )
        {
            for ( int i = 0; i < 10; i++ )  x.get().push_back( i );
        }
    }
};
 
int main()
{
    A a;
    
    for ( auto x : a.a ) std::cout << x << ' ';
    std::cout << std::endl;
    
    for ( auto x : a.b ) std::cout << x << ' ';
    std::cout << std::endl;
    
    for ( auto x : a.c ) std::cout << x << ' ';
    std::cout << std::endl;
 
    return 0;
}
Topic archived. No new replies allowed.