How to write to std::vector

For several reasons I like to try std::vector rather than std::array.
The following example does not set the e_use state of all entries with value 12 to false. Vector remains unchanged:

Use = 1 Name = Lisa
Use = 1 Name = Rose
Use = 0 Name = Jule
Use = 1 Name = Lisa
Use = 1 Name = Rose
Use = 0 Name = Jule

How do I have to change i.e_use=false to make it working ?

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
35
36
37
38
39
40
41
42
43
 #include <iostream>
#include <string>
#include <vector>

struct r_data  {
                     bool        e_use;
                     std::string e_name;
                     double      e_value;
               };

std::vector<r_data> cpp_lut {
                                  {true, "Lisa",10},
                                  {true, "Rose",12},
                                  {false, "Jule",13}
                            };

void lut_dump(void)
{
    for ( auto i : cpp_lut )
    {
        std::cout<<"Use = "<<i.e_use<<" Name = "<<i.e_name<<std::endl;
    }
}

void exclude ( uint no )
{
    for ( auto i : cpp_lut )
    {
        if (i.e_value == no) i.e_use = false;
    }
}

int main()
{
    lut_dump();         // vector before change
    exclude (12);       // set use of all entries with value 12 to false
    lut_dump();         // vector after change
}


 

On line 27 you need a reference:

for ( auto& i : cpp_lut ) // Note: &

Currently you modify a copy which will be lost as soon as the for loop ends.

I would recommend to use the actual data type which might be less confusing.

for ( r_data& i : cpp_lut )
many thanks. I was not aware that for loop is same than passing function parameters by value or by reference
It's the same for regular variables too.

1
2
auto a = cpp_lut[0]; // a is a copy of cpp_lut[0]
auto& b = cpp_lut[0]; // b is a reference to cpp_lut[0] 
if it helps, auto is just a type.
its the same as
int a = x; //copy
vs
int &a = x; //reference

auto just tells the compiler to determine that it is 'int' instead of 'double' or 'myclass' or 'somefunkyreallylongandweird::iterator' etc.
auto is just a type
auto is not a type. It's a keyword that is used to deduce a type.
Topic archived. No new replies allowed.