0

I'm new to C++, coming from C. How do I access each element of each struct in a std::list created with the <list> library?

#include <iostream>
#include <cstdlib>
#include <fstream>
#include <list>
#include <funcoes.h>

using namespace std;

typedef struct candidato{
    int inscricao;
    int idade;
    int cod;
    int nota;
 }candidato_c;

int main(){
    list<candidato_c> l;
    startlist(l);
}

funcoes.h

void startlist (list<candidato_c>& lista1){
    //How to access each element of each index?
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
  • 1
    See [the reference](https://en.cppreference.com/w/cpp/container/list) for all of the member functions `list` provides for getting access to the elements. – NathanOliver Sep 17 '20 at 14:42
  • 4
    If you want to access elements at particular indexes then you've chosen the wrong data structure. For indexed access you should use `vector` – john Sep 17 '20 at 14:46
  • 1
    `typedef struct candidato {` In c++ you don't need the typedef. `struct candidato {` is sufficient. – drescherjm Sep 17 '20 at 14:52
  • 1
    btw your list is empty, there are no elements to be accessed. Once you add some you could use a range based for loop for example – 463035818_is_not_an_ai Sep 17 '20 at 14:57
  • Welcome to SO! Since you're [starting with C++](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)... – ggorlen Sep 17 '20 at 18:36

1 Answers1

1

This is how to to access each element

struct candidato {
    int inscricao;
    int idade;
    int cod;
    int nota;
 };

int main(){
    list<candidato> l;
    startlist(l);
}

static void startlist(const std::list<candidato>& lista1) {
    for (const candidato& c : lista1)
    {
        std::cout << c.cod << std::endl;
    }
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
Gearoid
  • 76
  • 5