+ All Categories
Home > Documents > Computational Biology, Part B C, C++, Java Review Zia Khan Robert F. Murphy Copyright 2001. All...

Computational Biology, Part B C, C++, Java Review Zia Khan Robert F. Murphy Copyright 2001. All...

Date post: 13-Dec-2015
Category:
Upload: teresa-miles
View: 217 times
Download: 1 times
Share this document with a friend
Popular Tags:
22
Computational Biology, Part B C, C++, Java Review Zia Khan Zia Khan Robert F. Murphy Robert F. Murphy Copyright Copyright 2001. 2001. All rights reserved. All rights reserved.
Transcript

Computational Biology, Part B C, C++, Java Review

Computational Biology, Part B C, C++, Java Review

Zia KhanZia KhanRobert F. MurphyRobert F. Murphy

Copyright Copyright 2001. 2001.

All rights reserved.All rights reserved.

What exactly are we reviewing? Stuff you should know already.

What exactly are we reviewing? Stuff you should know already.

C, C++, JavaC, C++, Java Pointers and ReferencesPointers and References File I/OFile I/O String ManupulationString Manupulation Simple line-by-line parsingSimple line-by-line parsing

Command-line ArgumentsCommand-line Arguments

Pointers and References: What do I need to know?

Pointers and References: What do I need to know?

C/C++ PointersC/C++ Pointers Allocating MemoryAllocating Memory Using pointers to Using pointers to structstruct's and 's and classclass's's Passing Passing structstruct's and 's and classclass's to functions's to functions

Java ReferencesJava References Allocating MemoryAllocating Memory Passing around Passing around classclass's to and from functions's to and from functions

Pointers: Allocating MemoryPointers: Allocating Memory

CC char *alloc_string = calloc(sizeof(char) * string_length); // clears memorychar *alloc_string = calloc(sizeof(char) * string_length); // clears memory struct AntProtein *antgut = malloc(sizeof(struct AntProtein));struct AntProtein *antgut = malloc(sizeof(struct AntProtein)); free(antgut); // to free allocated memoryfree(antgut); // to free allocated memory

C++C++ char *alloc_string = new char[string_length];char *alloc_string = new char[string_length]; AntProtein *antgut = new AntProtein;AntProtein *antgut = new AntProtein; AntObject *bullet_ant = new AntObject(AntObject *bullet_ant = new AntObject("Fear me I am bullet ant!!!""Fear me I am bullet ant!!!");); delete[] alloc_string; // don't forget the [] when you free arraysdelete[] alloc_string; // don't forget the [] when you free arrays delete antgut;delete antgut;

Pointers: Using struct's and class'sPointers: Using struct's and class's

C: All you can do is access membersC: All you can do is access members struct ANTstruct*ant = malloc(sizeof(ANTstruct));struct ANTstruct*ant = malloc(sizeof(ANTstruct)); ant->leg_count = 6;ant->leg_count = 6;

C++: Get Members and Call Member C++: Get Members and Call Member FunctionsFunctions

ANTObject *ant = new AntObject(ANTObject *ant = new AntObject("Bullet ant""Bullet ant");); ant->leg_count = 6; // if leg_count is public you can do thisant->leg_count = 6; // if leg_count is public you can do this ant->Run();ant->Run();

Pointers: FunctionsPointers: Functions It's all about passing a variable that allows direct access to to a point in It's all about passing a variable that allows direct access to to a point in

memory. That means you can change the memory around. memory. That means you can change the memory around. Passing pointers to a function is "passing by reference." You want to change Passing pointers to a function is "passing by reference." You want to change

what you passed around.what you passed around. If you don't like working too hard, you're probably going to pass around If you don't like working too hard, you're probably going to pass around structstruct's 's

and and classclass's and maybe arrays. I will show you examples on the next slide.'s and maybe arrays. I will show you examples on the next slide. A pointer's memory sticks around even if you leave the scope of a function. A pointer's memory sticks around even if you leave the scope of a function.

Deallocate when you've passed it to some other function.Deallocate when you've passed it to some other function. Anything can be changed into a pointer by using the ampersand "&pointer" Anything can be changed into a pointer by using the ampersand "&pointer" You really should know about this already. If you totally forgot, You really should know about this already. If you totally forgot, USE JAVA USE JAVA

instead. If you don't know Java this is a really good time to learn it. instead. If you don't know Java this is a really good time to learn it. Pointers can and will make you cry.Pointers can and will make you cry.

Pointers: Functions (examples)Pointers: Functions (examples) C/C++ Passing Around ArraysC/C++ Passing Around Arrays

void study_ants(int *antspecies){void study_ants(int *antspecies){ *(antspecies + northamerica) = toomanytocount;}*(antspecies + northamerica) = toomanytocount;}

void study_ants(int antspecies[]){void study_ants(int antspecies[]){ Antspecies[northamerica] = toomanytocount;}Antspecies[northamerica] = toomanytocount;}

C Passing Around C Passing Around structstruct's's int red_ant ( struct AntSTRUCT *ant){int red_ant ( struct AntSTRUCT *ant){

if(ant->color == red) return 1; if(ant->color == red) return 1; Return 0;}Return 0;}

Pointers: Functions (examples, continued)

Pointers: Functions (examples, continued)

C++ Passing Around C++ Passing Around classclass's's void start_foraging(AntObject *ant){void start_foraging(AntObject *ant){

ant->forage();}ant->forage();} AntEgg *Queen(){AntEgg *Queen(){

return new AmEgg;}return new AmEgg;} Don't make functions that look like this unless you know what your Don't make functions that look like this unless you know what your

doingAntEgg &Queen() or AntEgg&Queen()doingAntEgg &Queen() or AntEgg&Queen() How to cheat and pass by reference in C++!!!!How to cheat and pass by reference in C++!!!!

void cheater_cheater_pumpkin_eater(pumpkin &p){void cheater_cheater_pumpkin_eater(pumpkin &p){ pumpkin.smashing(); pumpkin.changeme = 1;}pumpkin.smashing(); pumpkin.changeme = 1;}

References: Allocating MemoryReferences: Allocating Memory

Treat references as "placeholders" for java Treat references as "placeholders" for java objects.objects.

Ant bullet_ant = new Ant bullet_ant = new bullet_ant(Ant.FEIRCE);bullet_ant(Ant.FEIRCE);

int[][] antgrid;int[][] antgrid; antgrid = new int[10][8];antgrid = new int[10][8];

You don't need to free memory in Java the You don't need to free memory in Java the garbage collector will do it for you.garbage collector will do it for you.

References: FunctionsReferences: Functions

This will not work the way it should. References have This will not work the way it should. References have nothing to do with memory addresses.nothing to do with memory addresses.

void broken_swap(Object a, Object b){void broken_swap(Object a, Object b){ Object tmp; Object tmp; tmp = a; a = b; b = tmp; } tmp = a; a = b; b = tmp; }

To return multiple objects. Delcare a new class.To return multiple objects. Delcare a new class. class ReturnME{ Object a; Object b};class ReturnME{ Object a; Object b}; ReturnMe multipleObjects(){ReturnMe multipleObjects(){

ReturnME me = new ReturnMe();ReturnME me = new ReturnMe(); me.a = new Object(); me.b = new Object(); me.a = new Object(); me.b = new Object(); return me;}return me;}

File I/O: Opening a FileFile I/O: Opening a File

JavaJava import Java.io.*;import Java.io.*; BufferedReader file = new BufferedReader(new BufferedReader file = new BufferedReader(new

FileReader("FileReader("AntDNA.txtAntDNA.txt"));"));

CC #include <stdio.h>#include <stdio.h> FILE *file = fopen("FILE *file = fopen("AntDNA.txtAntDNA.txt", "r+"); /* open for reading and writing */", "r+"); /* open for reading and writing */

C++C++ #include <fstream> and #include <iostream>#include <fstream> and #include <iostream> fstream file("fstream file("AntDNA.txtAntDNA.txt");");

File I/O: Reading a LineFile I/O: Reading a Line

JavaJava String line = file.readLine();String line = file.readLine();

CC Give me a second. It's on the next slide.Give me a second. It's on the next slide.

C++C++ #include <fstream> and #include <iostream>#include <fstream> and #include <iostream> char line[256]; file.getline(line, 255);char line[256]; file.getline(line, 255);

File I/O: Reading a Line (in C)File I/O: Reading a Line (in C)

int fgetline(FILE *f, char *s, int l){int i; char ch;for(i = 0; i < l; i++){

ch = (char)fgetc();if(ch == EOF) return -1;if(ch == '\n') break;s[i] = ch;

}return l;

}

File I/O: Closing a FileFile I/O: Closing a File

JavaJava file.close();file.close();

CC fclose(file);fclose(file);

C++C++ file.close();file.close();

Closing and opening a file repositions the file pointer to the Closing and opening a file repositions the file pointer to the beginning of the file. You shouldn't have to do any fancy beginning of the file. You shouldn't have to do any fancy file random access. If you do, you're working to hard.file random access. If you do, you're working to hard.

Strings: VaritiesStrings: Varities

C: good old char*C: good old char* char *str = malloc(sizeof(char) * 31); // 30 character string, dnamically char *str = malloc(sizeof(char) * 31); // 30 character string, dnamically

allocatedallocated char str[31];char str[31]; char *str =char *str = "Computational Biology" "Computational Biology";; // length of string + null characterC // length of string + null characterC

C++: the string classC++: the string class #include <string>#include <string> string my_str;string my_str; const char *my_old_c_self = my_str.c_str(); const char *my_old_c_self = my_str.c_str(); // when you need a char*// when you need a char*

Java: java.lang.StringJava: java.lang.String String my_string = String my_string = "Use me!""Use me!";;

Strings: ManipulationStrings: Manipulation

LengthLength C: strlen(str);C: strlen(str); C++: my_str.length();C++: my_str.length(); Java: my_sring.length();Java: my_sring.length();

ConcatinationConcatination C: strcat(str1, str2);C: strcat(str1, str2); C++: ant = wasp + evolution;C++: ant = wasp + evolution; Java: sing = a + song;Java: sing = a + song;

More TricksMore Tricks C: "man string" on a Unix machineC: "man string" on a Unix machine C++: http://www.sgi.com/Technology/STL/basic_string.htmlC++: http://www.sgi.com/Technology/STL/basic_string.html Java: Consult the API reference!!Java: Consult the API reference!!

http://java.sun.com/docshttp://java.sun.com/docs

Parsing: Line-by-LineParsing: Line-by-Line

EasiestEasiest and and dirtiestdirtiest way of parsing a way of parsing a file.file.

1. Read in a line from a file.1. Read in a line from a file. 2. Parse the information in that line.2. Parse the information in that line. 3. If necessary keep reading more 3. If necessary keep reading more

lines.lines.

Parsing: Control LoopParsing: Control Loop

We want to keep reading a file until we reach the end of the file.We want to keep reading a file until we reach the end of the file. C: char line[256];C: char line[256];

whilewhile(!feof(file)){ fgetline(file, line,255);(!feof(file)){ fgetline(file, line,255);// see slide for // see slide for getlinegetline }; };

C++: string line;C++: string line; whilewhile(!file.eof()){ line = file.getline(); (!file.eof()){ line = file.getline(); // do stuff// do stuff }; };

Java: String line;Java: String line; whilewhile(true){(true){ try try{ line = file.readline(); } { line = file.readline(); }

catchcatch(IOException e){ (IOException e){ breakbreak; } ; } // do stuff// do stuff }; };

Parsing: Data From A LineParsing: Data From A Line Example: Example: "DATA 03510 BLAH 0.325""DATA 03510 BLAH 0.325" C: #include <string.h>C: #include <string.h>

char *tok = strtok(line);char *tok = strtok(line); // get a token (e.g. DATA, // get a token (e.g. DATA, 03510, etc.)03510, etc.)

Int n = atoi(tok); Int n = atoi(tok); // convert token to an integer// convert token to an integer float f = atof(tok); float f = atof(tok); // convert token to a float// convert token to a float

C++: #include <strstream>C++: #include <strstream> string d; int c; string d2; float f;string d; int c; string d2; float f; strstream parseline(line.c_str());strstream parseline(line.c_str()); parseline >> d >> c >> d2 >> f;parseline >> d >> c >> d2 >> f; if(parseline.bad()) return; if(parseline.bad()) return; // error// error

Parsing: Data From A Line (cont)Parsing: Data From A Line (cont)

Java: import java.io.*; // you can also use java.util.StringTokenizer Java: import java.io.*; // you can also use java.util.StringTokenizer String d; int c; String d; int c; StreamTokenizer parser = new StreamTokenizer(new StreamTokenizer parser = new StreamTokenizer(new

StringReader(line));StringReader(line)); if(parser.nextToken() == StreamTokenizer.TT_WORD)if(parser.nextToken() == StreamTokenizer.TT_WORD)

d = parser.sval;d = parser.sval; if(parser.nextToken() == StreamTokenizer.TT_NUMBER)if(parser.nextToken() == StreamTokenizer.TT_NUMBER)

• c = (int)parser.nval;c = (int)parser.nval;

Parsing: Data From Multiple Lines

Parsing: Data From Multiple Lines

You need something called a state variable.You need something called a state variable. This switch statement goes in your control loop.This switch statement goes in your control loop. switchswitch((state_variablestate_variable){){

casecase PARSING_DATA: PARSING_DATA: breakbreak;; casecase PROTEIN_DATA: PROTEIN_DATA: breakbreak;; casecase GENE_DATA: GENE_DATA: breakbreak;;

}} Different parsing code goes in between case and break.Different parsing code goes in between case and break. If you're in the GENE_DATA state you can parse multiple If you're in the GENE_DATA state you can parse multiple

lines and fill a struct or class with gene data that might span lines and fill a struct or class with gene data that might span multiple lines.multiple lines.

Command-line ArgumentsCommand-line Arguments

C/C++C/C++ intint main( main(intint argc, argc, charchar *argv[]) *argv[]) Using getopt. This makes things easy, but you're Using getopt. This makes things easy, but you're

on your own. Type the following on a unix on your own. Type the following on a unix machine.machine.

man 3 getopt man 3 getopt

JavaJava public static void public static void main (String args[])main (String args[])


Recommended