Hello,
suppose i have a test.txt file that contains
1 0 3
2 1 4
3 2 5
and i want this to be taken into my main file which reads the first column and stores it in its own array. then second column in its own array. then third column in its own array. so in my main it should be
int a[100]={1,2,3};
int b[100]={0,1,2};
int c[100]={3,4,5};
i was thinking of using a vector that took vectors of ints and every number will pushback and then every 3 read numbers the vector would move back to vector[0] and push_back the element
there are lots of ways to do it.
there is very likely a slick way to read the whole mess into a valarry and slice on it.
it is also trivial to do a transpose in place on a 2-d vector.
I have a habit of reading and processing apart, rather than read a little process a little strategy. I find it works more efficiently (granted we don't care for 9 items). Lines of random text processed line-wise are an exception for a number of reasons.
I agree that vectors would probably be a good idea. However look at your first snippet, how many arrays to you propose to use there? How many arrays are you using in your more complete snippet?
the problem with this code is if i use std::vector<std::vector<int>> it wont work
i want my program to have like
at vector 0 to have 1 0 3
vector 1 to have 2 1 4
vector 2 to have 3 2 5
but my program is just having 1 0 3 2 1 4 3 2 5 like a 1 d vector instead of 2 d
Why do you think a vector<vector<int>> is the correct solution?
at vector 0 to have 1 0 3
vector 1 to have 2 1 4
vector 2 to have 3 2 5
That looks like three vectors, not two.
Perhaps you should consider sticking with a single vector for each column for now, instead of trying to bring in the complexity of multidimensional vectors/arrays.
but my program is just having 1 0 3 2 1 4 3 2 5 like a 1 d vector instead of 2 d
That's because you're only using a single single dimensional vector. By the way your "array" is a three dimensional "array" not 1 or 2.
Use three single dimensional vectors and read each element into the correct element of the correct vector (think about using multiple loops for your reading).
Here. assuming the text file is as your first post:
you can add fluff like checking file there, figuring out how many things per row, whatever details... sorry used v1-3 for your a,b,c whatever you want to name them.
its harder to read the file than to get your 3 containers.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{
ifstream f("x.txt");
valarray<int> v(9);
for(int i = 0; i < 9; i++)
f>> v[i];
valarray<int> v1 = v[slice(0,3,3)]; //start at 0, get 3, 3 apart
valarray<int> v2 = v[slice(1,3,3)]; //start at 1, get 3, 3 apart
valarray<int> v3 = v[slice(2,3,3)]; //start at 2, get 3, 3 apart
for(int i = 0; i < 3; i++) cout << v1[i] << endl;
for(int i = 0; i < 3; i++) cout << v2[i] << endl;
for(int i = 0; i < 3; i++) cout << v3[i] << endl;
}