Reputation: 67
I can show the values stored in vector mem (see edited code). How can i store the values in vec.name? It's the syntax that i have problem with. Specifically defining the container for vec.name as well as storing data in it using push_back.
#include <vector>
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <set>
using namespace std;
//struct vec {
// int name;
//};
//vector<vec> mem;
vector<int> mem;
size_t nx, ny, nz;
void read(const char * name)
{
ifstream file(name);
cout << "read file " << name << endl;
size_t Nx, Ny, Nz;
file >> Nx >> Ny >> Nz;
int c=0;
size_t itens;
for (size_t z = 0 ; z < Nz ; ++z) {
for (size_t y = 0 ; y < Ny ; ++y) {
for (size_t x = 0 ; x < Nx ; ++x) {
c=c+1;
file >> itens;
//mem[c].name = itens;
mem.push_back(itens);
}
}
}
}
int main ()
{
read("names.txt");
for(int i=0;i<26;i++){
cout << mem[i] <<endl;
}
cout << "Computation done." << endl;
return 0;
}
Upvotes: -4
Views: 324
Reputation: 27250
Update following your comment and your Edit:
You are getting a Segmentation Fault on the first time you are on the line mem[c].name = itens;
because you are trying to access mem[1]
which you haven't created. In order to access an element of a vector you need to add it to a vector, usually using push_back
. Since you are trying to access the second element of the vector, you should call push_back
at least twice beforehand.
You probably also need to do some additional fixes in your algorithm, but I will leave it to you.
My original answer:
Your container is vector<vec> name
.
You can access its n'th element by name[n]
. You can access n'th element's mm
member variable by name[n].mm
The code that you are using in your snippet (vec[c].name
) is wrong.
Upvotes: 2