MY FAQ About C ++CMFC.

xiaoxiao2021-03-14  181

My FAQ About C / C / MFC Programming

1.

How to pass Iterator

What is the value in the structure?

such as,

Map , int_value> :: item;

by

iTer

Access the value of the object it refers to, the practice is as follows:

INT LEFT_INT = (* iter) .first.first;

INT RIGHT_INT = (* iTer) .first.right;

INT value_int = (* iter). Second;

2.

How to pass Iterator

Get the subscript or the opposite.

E.g,

Vector :: item;

Int index = item-vec.begin ();

iTer = vec.begin () index;

3.

How to get random integers?

EXAMPLE:

#include

#include

Main ()

{

INT BIG_NUM = 100;

SRAND (NULL);

While (true) {

COUT << rand_num = rand ()% 100; // Output 0 ~ 99 integer

}

}

4.

How to give vector

Preset size?

If you know in advance

Vector

The space required is not required to grow in order to save space. Definition

Vector

After you can call

RESEAVE

Function presets its size.

Vector vec;

VEC.RESEARVE (100); //

Preset

100

5.

Predicate Function Object in generic container and generic algorithm

Predicate function object)

How to write?

For example, in calling generic containers

Map

Or generic algorithm

: Sort, Lower_Bound, Upper_bounder, Equal_RANG

When you need to specify the parameters:

"Binarypredicate _comp"

.

How to use it? Use a use

Sort

Example to explain it.

There is a structure

Node

Inside a shaped value, one

String

Value. I want to think about one now

Vector

Type object

VEC_NODE

Inside the content

Sort

put in order. There are three ways.

method

1:

Not give

Sort

Explicitly provide comparison guidelines, then automatically call

VEC_NODE

Inside the type

"<"

Operation, if there is no overload

"<"

The compiler is wrong.

method

2:

Explicitly provide comparison criteria

,

Provided by a general function.

method

3:

Explicitly provide comparison criteria

,

use

Function Object

To provide.

method

2, 3

In fact,

Use

Function Object

There are many advantages than the general function pointers.

Function Objects (Also Called "Functors") Are ORDINARY CLASS Objects That Overload The () Operator. Thus, SyntActical, They Behave Like Ordinary Functions.

for

Map

Container, because it itself is an ordered container, so it is also necessary to define the user-defined more complicated structure.

Predicate

But for

Key

Type comparison.

But generally

Key

for

Int, or

Key

Type

PAIR

in the case of,

Map

The structure has a default order arrangement.

The sample code is as follows:

#include

#include

#include

#include

Using namespace std;

Typedef struct node {

Int value;

String Key;

PUBLIC:

BOOL Operator <(const node n) // method 1: Overload "<" operator

{

Return Value> N.Value;

}

} node;

Class Func2 {// Method 2: Define Function Object

PUBLIC:

Bool Operator () (Const Node N1, Const Node N2)

{

Return n1.value> n2.value;

}

}

BOOL FUNC3 (Node N1, Node N2) // Method 3: Define General Functions

{

Return n1.value> n2.value;

}

void main ()

{

Vector intVec;

Node N1;

N1.key = "hf4";

N1.Value = 4;

INTVEC.PUSH_BACK (N1);

N1.key = "hf2";

N1.Value = 2;

INTVEC.PUSH_BACK (N1);

N1.key = "hf1";

N1.Value = 1;

INTVEC.PUSH_BACK (N1);

n1.key = "hf3";

N1.Value = 3;

INTVEC.PUSH_BACK (N1);

N1.key = "hf5";

N1.Value = 5;

INTVEC.PUSH_BACK (N1);

Sort (intVec.begin (), intVec.end ()); // method 1: overload "<" operator

Sort (intVec.begin (), intVec2 ()); // method 2: Define Function Object, pay attention to add '()'

Sort (intVec.begin (), intVec3); // method 3: Define general functions

For (int i = 0; I

{

COUT << intVec [i] .value << "/ t";

}

}

6.

What are the two-point lookup algorithms in the generic algorithm? how to use?

Such as

Lower_Bound, Upper_Bound, Equal_Range

This type.

A lower limit of finding a gave interval, one upper limit, one is the interval.

Do you want to see if you need to write according to the situation.

Predicate,

But some subtle problems also need to pay attention to

Lower_Bound

Usage is used.

Typedef struct bigramnode {

INT leftwrdid;

INT RIGHTWRDID;

Double logprob;

} BIGRAMNODE;

Class Comp

{

PUBLIC:

Bool Operator () (Const Bigramnode N1, Const Int WordID)

{

Return n1.rightwrdid

}

// Notes point 1: The comparison between the two directions should be considered. Bool Operator () (Const BiGramnode N2)

{

Return N2.rightwrdid

}

}

Vector :: item binodeiter;

Vector :: item Startiter = m_vbigramnodes.begin () BIGRAMSTARTP;

Vector :: item Enditer = m_vbigramnodes.begin () BIGRAMSENDP;

//

be careful

2

: If the value in the range you want to find is not repetitive, then you should first look at whether the tail iterator refers to

//

Ask.

IF (* enditer) .rightwrdid == RightwordID)

{

Return (* enditer) .logprob;

}

Binodeiter = Lower_Bound (Startiter, Enditer, RightwordId, Comp ());

// Notes 3: After the found two points, the result is the tail of the findings and is not given. Because // If you can't find it, you will return to the tail of the lookup interval.

IF (binodeiter! = Enditer && (* binode) .rightwrdid == RightwordID)

{

Return (* binodeiter) .logprob;

}

7.

1.

What is commonly used in reading and writing?

Summary here first

C / C / MFC

Chinese text handling common file read and write.

1. C

inside

a) In the standard C, all file read and write operations are performed through the file pointer, ie FILE * FP;

b) The file mode is binary or text mode, each processing method is the same, such as using FSCANF / FPRINTF to open reading and writing binary text or text mode text, its effect is the same. (Personal opinion, view after simple test)

c) Read and write the disk file with the fscanf / fprintf function, easy to use, easy to understand, but due to the input ASCII characters to the binary number, the binary number is converted to the ASCII character, and it takes more time, so In the case where memory is frequently exchanged with disk, it is best not to use the Fprintf and FSCANF functions, and use the FREAD and FWRITE functions.

d) file

Opening and closing file

i.

turn on:

fp = fopen (filename,

File usage

)

If it is not successful, return an empty pointer

NULL.

II.

shut down:

Fclose (fp);

To develop the habit of closing the file, because

c

The number of files that the compilation system allows open files is limited and the data in the lost cache can be prevented.

Iii.

The judgment file ends:

1. While (! Feof (fp)) {

If the file is not ended

}

e) There are three ways to read and write the file.

i.

According to characters

(

string

)

Read and write

1. CHAR CH = FGETC (FP); FPUTC (CH, FP);

2. Char * FGETS (Char * String, INT N, FILE * stream);

3. Int fputs (const char * string, file * stream); 4. If you want to read a line, use fgets (Str, ENOUGH_BIG_NUM, FP); because the FGETS touches the NewLine character ('/ n') automatically truncated.

II.

Read and write files according to data block

1. Fread (Buffer, Size, Count, FP);

2. FWRITE (Buffer, Size, Count, FP);

3. Return Value: The number of data blocks read / written

4. Example: Struct MT * EBMT, * SMT;

a) file * fp;

IF ((fp = fopen ("mt_method.dat", "wb ")) == NULL) {

Printf ("Open Error");

Return;

}

EBMT = New MT;

SMT = New MT;

....//

Value

//

Write file

FWRITE (EBMT, SIZEOF (Struct MT), 1, FP);

FWRITE (SMT, SIZEOF (STRUCT MT), 1, FP);

Struct MT * new_ebmt, * new_smt;

// read in

Fread (New_EBMT, SIZEOF (Struct MT), 1, FP);

Fread (New_SMT, SIZEOF (Struct MT), 1, FP);

Fclose (fp);

Iii.

Read and write in format

FSCANF (

File pointer, format control parameter, address parameter list

)

;

2. FPRINTF

File pointer, format control parameter, address parameter list

)

;

3. File * stream; char Str [];

FPrintf (stream, "% s% ld% f% C", "a-string", 65000, 3.14159, 'x');

If you want to enter a word each time:

FSCANF (FP, "% S", STR);

because

Fscanf

Can

White-Space Characters: Blank (''); tab ('/ t'); or newline ('/ n').

Truncate. But pay attention to

Fscanf

When taking words, pay special attention to whether the last word will take twice. For example, a few lines of space lines at the end of the text.

If the code is

Void main (void)

{

File * stream;

Char line [100];

IF ("" "" = fopen, "r"))))! = NULL)

{

While (! Feof (stream))

{FSCANF (stream, "% s", line);

Printf ("% s # / n", line);

}

Fclose (stream);

}

}

Then the last word will be output twice, the reason is that the last time there is still a return line in the file, so

While

Circular, then

Fscanf

Did not take new words,

Line

Saved is still the previous word, then output again, then

While

The cycle is also terminated. So going to

Fscanf

The implementation is judged, here can judge whether or not the file is reached. Change the top of the black and black.

IF (FSCANF (stream, "% s", line)! = EOF) Printf ("% s # / n", line);

2. In C

a) c

In the input and output provides a rich stream library, specific information can be found

<< C Primer 3rd Edition >>

In the middle

20

chapter. Here, just briefly introduce common file flow operations.

b) Document open creation shutdown:

i.

enter

/

Open the creation of the file stream:

IFSTREAM in ("Input.txt");

or

IFStream in; in .open ("Input.txt");

or

FStream Outfile ("Output.txt", iOS_Base :: OUT)

,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,

FSTREAM OUTFILE ("Output.txt", iOS_BASE :: App);

Judgment is open correctly:

IF (! in) CERR << "Input File Open Error./N";

II.

shut down:

FileStream.close ();

c) read into one or a word

IFStream Infile ("Infile.txt");

String line, Next_word;

GetLine (Infile, Line) //

The third parameter separator is default

'/ N'

//

If you use

White Characters ('/ t', '', '/ n')

segmentation

,

So reading a word

Infile >> next_word;

d) output

i.

General use

Outfile << OUT_CONTENT;

enough.

3. In VC / MFC

a) First we see the inheritance relationship diagram of the document in the MFC hierarchy: The two file types commonly used in our text handling actual operation are CFILE and CSTDIOFILE.

b) CSTDIOFILE

Inheritance

CFILE,

and

Cfile

Directly Provides UnBuffered, Binary Disk INPUT / OUTPUT Services, And It Indirectly Supports TEXT Files and Memory Files Through ITS Derived Classes

Use cfile and its derived classes for General-Purpose Disk I / O. Use ofstream or Other Microsoft Iostream Classes for Formatted Text Sent To a Disk file.

Cfile

apart from

Read / Write

In addition, there are many functions, such as

GetFilePath, getFilename

Wait.

Cstdiofile

A CSTDIOFILE Object Represents a c run-time stream file as opened by the run-time function fopen. Stream files are buffered and can be opened in Either text mode (the default) or binary mode.

Text mode provides special processing for carriage return-linefeed pairs. When you write a newline character (0x0A) to a text-mode CStdioFile object, the byte pair (0x0D, 0x0A) is sent to the file. When you read, the byte pair (0x0a, 0x0d) IS translated to a single 0x0a byte.cstdiofile

ratio

Cfile

More than two functions are available:

Text Read / Write

Readstring

Reads a Single Line of Text.

WriteString

Writes a single line of text.

8.

8. Vector.Rserve (n)

And vector.resize (n)

The former is reserved

N

Space, does not fill, return it at this time

Vector.size ()

still is

0,

And this is going to access an element, such as

Vector [10]

If there is a runtime error. The latter not only reserved space, but also filled the default value for the constructor corresponding to each spatial call element. Actually

Push_back

In

N

An acknowledgment. Also remember, just defined one

Vector

When it is still used yet

Resize ()

When such a function is filled with any elements, the elements are needed to be used to use it.

Push_back ()

Can't pass

Vector [index] = item;

Such

operating.

9.

How to make the program run time

Example program

:

#ifdef

Win32

// the filetime structure is a 64-bit value representing the number of

// 100-nanoseconds. One nanosecond = 10e-9 seconds.

TYPEDEF __INT64 INT64;

Filetime ftdummy, ftkernel, ftuser;

GetProcesstimes (getCurrentProcess (), & ftdummy, & ftuMmy, & ftkernel, & ftuser;

Printf ("real% .3fs / n", double (clock () - startclk) / clocks_per_sec);

Printf ("User%. 3FS / N", (int 64 (ftuser.dwhighdatetime << 32) | ftuser.dwlowdatetime) / 1e7);

Printf ("sys% .3fs / n", (int 64 (ftkernel.dwhighttime << 32) | ftkernel.dwlowdatetime) / 1e7);

#ENDIF

Where clock () is a function in "time.h",

StartCLK is a Clock_t type.

GetProcesstimes is a Windows API function that returns the current time used.

10. TBC

转载请注明原文地址:https://www.9cbs.com/read-129350.html

New Post(0)