Archive

Posts Tagged ‘C++’

stl Sort in C++; simple code for sorting the array of structures

February 18, 2009 mohsenam Leave a comment

Simple Code that shows how to use the C++ STL function sort()


<blockquote>
#include <iostream>
#include <algorithm>

using namespace std;

struct Numb{
double num;
int pos1;

bool operator &lt;(const Numb &amp;n1){
return num &lt; n1.num;
};
};
////////////////////////////////
void main(void){

Numb numb[10];

for(int i=0; i &lt; 10; i++){
numb[i].num = rand();
numb[i].pos1 = i;
}
cout &lt;&lt; endl &lt;&lt; "---------" &lt;&lt;endl;
for(int i=0; i &lt; 10; i++){
cout &lt;&lt; " " &lt;&lt; "(" &lt;&lt; numb[i].pos1 &lt;&lt; ") " &lt;&lt; numb[i].num;
}
cout &lt;&lt; endl &lt;&lt; "---------" &lt;&lt;endl;

std::sort( numb, numb+10);
cout &lt;&lt; endl &lt;&lt; "---------" &lt;&lt;endl;
for(int i=0; i &lt; 10; i++){
cout &lt;&lt; " " &lt;&lt; "(" &lt;&lt; numb[i].pos1 &lt;&lt; ") " &lt;&lt; numb[i].num;
}

cout &lt;&lt; endl &lt;&lt; "---------" &lt;&lt;endl;

}
Categories: STL, code Tags: , , , ,

(ReadShader)Simple File Reading Code in C++ with File Size buffer

April 5, 2008 mohsenam Leave a comment

//impressed by lighthouse 3d and help taken from sources on the internet.
//this is not my idea, not my full code.

//It reads the full file in single go.
#ifndef READSHADER_H
#define READSHADER_H
#include
#include

using namespace std;

char * readShader(char *fileName){

cout <<”nothing”;
ifstream input(fileName);
if(!input){
cout << endl << “UNABLE TO OPEN FILE ” << fileName <<endl;
return 0;
}

int st = input.tellg();
input.seekg(0, ios::end);
int end = input.tellg();
int fileSize = end – st;
if(fileSize <= 0){return 0;}

char *data = new char[fileSize+50];//50 added to just have buffer
memset(data, ”,fileSize+10);
input.seekg(0, ios::beg);

input.read(data,fileSize);
input.close();
data[fileSize]= ”; //appending the zero as the read does not append that
return data;

};
#endif