473,320 Members | 1,694 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

vector question

Hi! i'm a beginner user of c++ and i need some help. I use visual c++
6.0 on a p4 under windows 2000.

First, i read a text file with 3 fields: gestionnal age (GA), birth
weight (BW) and repetition (the number fo patient for specific GA and
BW). The file is ordered by GA and BW. I put each field in an vector.
GA took value between 22 and 44 and i want to create 2 others vector
(qcount, qcumulative) containing the number of patients for each GA
and the cumulative number of patients.

/************************************************** *************************
ex:
22 100 2
22 125 3
23 150 1
23 165 4
23 170 8
25 180 10

qcount=(5,13,10)
qcumulative=(5,18,28)
************************************************** **************************/

here's my code:
#include <stdio.h>
#include <stddef.h>
#include <stdlib.h>
#include <math.h>
#define pi 3.1415926

#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>

using namespace std;
main()
{
vector<int> vga;
vector<int> vrep;
vector<float> vweight;
/* add space between variables for output */
ostream_iterator <int> sortie( cout, " ");
/*FILE1 should be your data file, consisting only of gestational age,
birthweight and
number of repetition in integer format.
*/

/* output and input files */
ifstream input_file ("growth1sorted.txt", ios::in);
/* Import data */

if (!input_file)
{
cerr << "The file cannot be opened";
exit(1);
}
int temp_ga; int repet;
float temp_wt;
while (input_file >> temp_ga >> temp_wt >> repet)
{
vga.insert(vga.end(), temp_ga);
vweight.insert(vweight.end(), temp_wt);
vrep.insert(vrep.end(), repet);
}
/* close the file */
input_file.close();

....

DO I WORK WITH THE RIGHT CLASS (VECTOR) FOR THIS KIND OF TASK?

thanks
Jul 19 '05 #1
2 4385
"Justin" <ju*************@hotmail.com> wrote in message
news:a5**************************@posting.google.c om...
Hi! i'm a beginner user of c++ and i need some help. I use visual c++
6.0 on a p4 under windows 2000.

First, i read a text file with 3 fields: gestionnal age (GA), birth
weight (BW) and repetition (the number fo patient for specific GA and
BW). The file is ordered by GA and BW. I put each field in an vector.
GA took value between 22 and 44 and i want to create 2 others vector
(qcount, qcumulative) containing the number of patients for each GA
and the cumulative number of patients.
[snip]
DO I WORK WITH THE RIGHT CLASS (VECTOR) FOR THIS KIND OF TASK?

thanks


While it's good that you used a vector, I'd recommend making your program
more organized by making a single vector. You did something this:

vector<int> vga;
vector<int> vrep;
vector<float> vweight;
I'd recommend doing this:

struct patient
{
int vga;
int vrep;
float vweight;
};

vector <patient> patients;

It'll just make your program more organized.

-- MiniDisc_2k2
To reply, replace nospam.com with cox dot net.
Jul 19 '05 #2
In article <a5**************************@posting.google.com >,
ju*************@hotmail.com says...
Hi! i'm a beginner user of c++ and i need some help. I use visual c++
6.0 on a p4 under windows 2000.

First, i read a text file with 3 fields: gestionnal age (GA), birth
weight (BW) and repetition (the number fo patient for specific GA and
BW). The file is ordered by GA and BW. I put each field in an vector.
GA took value between 22 and 44 and i want to create 2 others vector
(qcount, qcumulative) containing the number of patients for each GA
and the cumulative number of patients.
[ ... ]
DO I WORK WITH THE RIGHT CLASS (VECTOR) FOR THIS KIND OF TASK?


You've already been advised to use a struct or class instead of three
separate vectors. I, however, would advise against using a vector for
the data, and use a multiset instead. My reasoning is pretty simple:
using a multiset simplifies some of the other operations you want to do.
As a first cut, I'd consider code something like this:

// warning: untested code.
class patient_data {
std::istream &read(std::istream &is) {
return is >> vga >> vrep >> vweight;
}

public:

friend std::istream &operator>>(std::istream &, patient_data &) {
return pd.read(is);
}

bool operator<(patient_data const &other) const {
return vga < other.vga;
}

operator int() { return vrep; }

int vga;
ing vrep;
float vweight;
};

bool read_data(std::set<patient_data> &pd, std::string fname) {
std::ifstream input_file(fname.c_str());
if ( ! input_file)
return false;

std::istream_iterator<patient_data> pd_in(input_file);
std::istream_iterator<patient_data> pd_end;

std::copy(pd_in, pd_end, std::inserter(pd, pd.end()));
return true;
}

int main() {
std::set<patient_data> pd;
typedef std::set<patient_data>::iterator pdi;

if ( !read_data(pd, "growth1sorted.txt")) {
std::cerr << "Unable to read data" << std::endl;
return EXIT_FAILURE;
}

std::vector<int> qcount;
std::vector<int> qcumulative;

std::pair<pdi, pdi> r(pd.begin(), pd.begin());

unsigned long total = 0;

while((r=std::equal_range(r.second->vga).first != pd.end()) {
int current = 0;

std::accumulate<r.first, r.second, current);
qcount.push_back(current);
total += current;
qcumulative.push_back(total);
}
}

The condition of the while loop is just a TAD on the gruesome side, but
I think I got it about right. The idea's a little complex, but not too
terrible. std::equal_range finds a range in which the keys (vga in our
case) compare equal, and returns iterators to the first and one beyond
the last item with that value. We initialize the second of the pair to
point to the beginning of the array, so the first time through, it finds
all the records with that value of vga. On the second and subsequent
iterations, it starts one past the last range it just processed, and
continues until the first iterator is set to end(), indicating that
we've processed all the data.

The processing itself uses std::accumulate to add up the values of vrep
for all the records in the range we've found. Since current is an int,
it attempts to treat the record as an int to add its value to current.
We allow that by providing a conversion to int that returns the value we
want added (vrep).

Note that since we're using std::multiset, there's no real need for the
data to be sorted and pre-processed as you're using it now -- the
multiset will sort the data during input, and counting elements instead
of adding up values of vrep would be just as easy (if anything, it would
be a bit cleaner).

--
Later,
Jerry.

The universe is a figment of its own imagination.
Jul 19 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Jessica | last post by:
Hi, I do not have a lot of experience with STL and I hope some of you might be able to help me on this seemingly elementary question. I have a vector of doubles (v1). I am trying to copy the...
10
by: Stefan Höhne | last post by:
Hi, as I recon, std::vector::clear()'s semantics changed from MS VC++ 6.0 to MS' DOT.NET - compiler. In the 6.0 version the capacity() of the vector did not change with the call to...
12
by: No Such Luck | last post by:
Hi All: I'm not sure if this is the right place to ask this question, but I couldn't find a more appropriate group. This is more of a theory question regarding an algorithm implemented in C, not...
24
by: toton | last post by:
Hi, I want to have a vector like class with some additional functionality (cosmetic one). So can I inherit a vector class to add the addition function like, CorresVector : public...
2
by: danielhdez14142 | last post by:
Some time ago, I had a segment of code like vector<vector<int example; f(example); and inside f, I defined vector<int>'s and used push_back to get them inside example. I got a segmentation...
9
by: Jess | last post by:
Hello, I tried to clear a vector "v" using "v.clear()". If "v" contains those objects that are non-built-in (e.g. string), then "clear()" can indeed remove all contents. However, if "v"...
7
by: nw | last post by:
Hi, We've been having a discussion at work and I'm wondering if anyone here would care to offer an opinion or alternative solution. Aparently in the C programming HPC community it is common to...
6
by: jmsanchezdiaz | last post by:
CPP question: if i had a struct like "struct str { int a; int b };" and a vector "std::vector < str test;" and wanted to push_back a struct, would i have to define the struct, fill it, and then...
13
by: prasadmpatil | last post by:
I am new STL programming. I have a query regarding vectors. If I am iterating over a vector using a iterator, but do some operations that modify the size of the vector. Will the iterator recognize...
6
by: Mr. K.V.B.L. | last post by:
I want to start a map with keys but an empty vector<string>. Not sure what the syntax is here. Something like: map<string, vector<string MapVector; MapVector.insert(make_pair("string1",...
0
by: ryjfgjl | last post by:
ExcelToDatabase: batch import excel into database automatically...
0
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: jfyes | last post by:
As a hardware engineer, after seeing that CEIWEI recently released a new tool for Modbus RTU Over TCP/UDP filtering and monitoring, I actively went to its official website to take a look. It turned...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Shællîpôpï 09 | last post by:
If u are using a keypad phone, how do u turn on JavaScript, to access features like WhatsApp, Facebook, Instagram....
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.