Iterating through vector of class with several elements

Hi,

I've looked through posts that are similar but struggle to find any that exactly help with my issue.

I've created a vector of a type of class with several (int) elements in it.

e.g.
class something
{
int a;
int b;
int c;
}

in main, I have:

vector<something> NewVec;
Something thing;

I believe that I've filled it up, but can't access each of the elements of each element of the vector.
I read in from a file, loaded them into an array and then placed them into:
thing.a = arrayelement[1];
thing.b = arrayelement[2];
thing.c = arrayelement[3];

Then I did a NewVec.push_back(thing);

I've put done this within a while() statement as there are a few lines of a, b & c.

Trying to print them out, though...

I've tried for_each(NewVec.begin(), NewVec.end(), ???)
In the spot of ??? I've tried running a function from the body of the program to print the out, a function from within the class and straight reference.

How should I reference each NewVec.a, NewVec.b and NewVec.c for each element of the vector?

Thanks.
Here is a simple demo.
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
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>

struct something
{
  int a;
  int b;
  int c;
};


int main(int argc, char *argv[])
{
  std::vector<something> v;

  v.push_back(something{1, 2, 3});
  v.push_back(something{4, 5, 6});
  v.push_back(something{7, 8, 9});
  v.push_back(something{10, 11, 12});

  // print vector method 1
  std::cout << "Vector elements - method 1\n";
  for (auto sth : v)
  {
    std::cout << sth.a << '\t' << sth.b << '\t' << sth.c << '\n';
  }
  // print vector method 2
  std::cout << "Vector elements - method 2\n";
  std::for_each(v.begin(), v.end(), [](const something sth){
    std::cout << sth.a << '\t' << sth.b << '\t' << sth.c << '\n';
  });
  system("pause");
  return 0;
}
Thanks.
I'll give that a go.
a function from within the class ...
printing with a class member method would not be recommended, for your code could look like:
1
2
3
4
something a;
a << std::cout; //precludes chaining
//instead of 
std::cout << a;  


Since you are working with class, not struct, take a look at overloading operator << as a friend
https://www.tutorialspoint.com/cplusplus/input_output_operators_overloading.htm
Last edited on
Topic archived. No new replies allowed.