473,769 Members | 5,742 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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_iterato r <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(vre p.end(), repet);
}
/* close the file */
input_file.clos e();

....

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

thanks
Jul 19 '05 #1
2 4432
"Justin" <ju************ *@hotmail.com> wrote in message
news:a5******** *************** ***@posting.goo gle.com...
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::istr eam &is) {
return is >> vga >> vrep >> vweight;
}

public:

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

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

operator int() { return vrep; }

int vga;
ing vrep;
float vweight;
};

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

std::istream_it erator<patient_ data> pd_in(input_fil e);
std::istream_it erator<patient_ data> pd_end;

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

int main() {
std::set<patien t_data> pd;
typedef std::set<patien t_data>::iterat or 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::e qual_range(r.se cond->vga).first != pd.end()) {
int current = 0;

std::accumulate <r.first, r.second, current);
qcount.push_bac k(current);
total += current;
qcumulative.pus h_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_rang e 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
11433
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 values to a 2D vector, of which every vector has the same length. I tried the following but I get a "System.NullReferenceException" error when I ran it.
10
7079
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 clear(), in DOT.NET the capacity() is reduced to 0.
12
3162
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 necessarily a C language question. I'm trying to break up a vector into an arbitrary number of subvectors, equal (or as near to equal) in size as possible. My problem occurs when the vector is not evenly divisible by the number of subvectors...
24
2960
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 vector<Corres>{ public: void addCorres(Corres& c); //it do little more than push_back function. }
2
3324
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 fault which I resolved by doing vector<vector<int example; example.push_back(vector<int>());
9
3759
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" contains built-in types (e.g. int), then "clear()" doesn't remove anything at all. Why does "clear()" have this behaviour? Also, when I copy one vector "v1" from another vector "v2", with "v1" longer than "v2" (e.g. "v1" has 2 elements and "v2" has...
7
3895
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 allocate multidimentional arrays like so: int *v_base = (int *) malloc(1000000*sizeof(int)); int **v = (int **) malloc(1000*sizeof(int *));
6
11616
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 push_back it, or could i pushback the two ints directly somehow? Thanks for all.
13
1927
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 this? I wrote the following program to test this out. #include <fstream> #include <iostream> #include <string>
6
7384
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", new vector<string>)); MapVector.insert(make_pair("string2", new vector<string>)); MapVector.insert(make_pair("string3", new vector<string>));
0
9423
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10210
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10043
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9861
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7406
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 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 a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6672
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3956
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
3
2814
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.