Effective Stl: Item 16: Know How To Pass Vector and String Data To

zhaozj2021-02-08  219

Since C WAS Standardized in 1998, The C Elite Haven¡ ¯TBEENTERRI-BLY

Subtle In Their Attempt to Nudge Programmers Away from Arrays

And toards vectors................ ¯VE Been Similarly Overt in Trying to Get Develop OPERS

To Shift from Char * Pointers to String Objects. There Are Good REA-SONS

For Making There Changes, Including The Elimination of Common

Programming Errors (See Item 13) and the Ability to Take Full Advan-TAGE

Of The Power of The Stl Algorithms (See, E.G., Item 31).

STILL, OBSTACLES Remain, And One of the Most Common Is The Existence

Of Legacy C Apis That Traffic IN Arrays and Char * Pointers Instead of Vec-Tor

And String Objects. Such Apis Will EXIST for a long time, so we must

Makepece with Themiffness. Weavesely.

Fortunately, IT¡ ¯S easy. If you have a vector v and you need to get a

Pointer to The Data IN v Thatcan Be Viewedasan Array, Just Use & V [0].

For a string s, the corresponding incarting is simply s.c_str (). But BUT

Read on. as The Fine Print In Advertising Offen Points Out, Certain

Restrictions apply.

Given

Vector v;

The Expression V [0] yields a reason to the first element in the vector,

SO & V [0] Is a Pointer to That First Element. The Elements in a Vector Are

Constrained by the C Standard to Be Stored in ContiGuous Memory,

Just Like an Array, SO IF We wish to Pass V to a c api tria om-thing

LIKE THIS,

Void Dosomething (const INT * PINTS, SIZE_T NUMINTS);

We can do it like this:

DOSMETHING (& V [0], v.size ());

Maybe. Probably. The only sticking point is if v is Empty. If it is, v.si ZE ()

Is Zero, And & V [0] Attempts to Produce a Pointer to Something That

Does not exist. not good. Undefined results. A Safer Way to Code Thecall IS: ഊ ഊ (! v.empty ()) {

DOSMETHING (& V [0], v.size ());

}

If You Travel in The Wrong Circles, You May Run Across Shady Charac-Ters

WHO WILL TELL You That You Can Use V.Begin () in Place of & V [0],

Because (these Loathsome Creatures Will Tell you) Begin Returns An ITER-ATOR

INTO The Vector, AndForVectors, Iterators Are Really Pointers. That. ¯S

OFTEN TRUE, But As Item 50 REAALS, IT¡ ¯S NOT Always True, and you shouth

NEVER RELY ON It. The return type of begin is an itrator, not a point,

And you sell never use beginen you you need to get a pointer to the

Data in a vector.if you. ¯Redeeterminedto typev.begi n () for Some Reason,

Type & * v.begin (), Because That Will Yield The Same Pointer AS & V [0],

Though IT¡ ¯S more work for you as a type and more obscure for mind

Trying to make Sense of Your code. frankly, if you. ¯RE HANGING OUT WITH

People who tell you to use v.begin () instead of & v [0], youneedto

Rethink your social circral.

The approach to getting a Pointer to Container Data That Works for Vec-Tors

ISN ¡ ¯T Reliable for strings, Because (1) The data for strings arenot

Guaranteed to Be Stored in ContiGuous Memory, and (2) THE INTERNAL

REPRESETATION OF A STRING IS Not Guaranteed to End With a NULL Charac-Ter.

This Explains The Existence of the String Member Function C_STR,

Which Returns a Pointer to the value of the string in a form designed

For C. We can thus pass a string s to this function,

Void Dosomething (const char * pstring);

LIKE THIS:

DOSMETHING (S.C_STR ());

THIS WORKS EVEN IF THE STRING IS OF Length Zero. In That Case, C_Str Will

Return a Pointer to a Null Character. It Also Works if the string has

Embedded nulls. if it does, howare, dosomething is likely to interpret

THE FIRST Embedded Null As The End of The String. String Objects Don ¯T

Care if the contain null characters, but char * -BASED C APIS DO.

Look Again At The Dosomething Declarations:

Void Dosomething (const INT * PINTS, SIZE_T NUMINTS);

Void Dosomething (const char * pstring);

In Both Cases, The Pointers Being Passed Are Pointers To Const.Thevec-Tor

OR string data area being passed to an api thing will read it, not mod-imp

It. this is by far the safESt thing to do. for strings, it ¯s the only thing

To do, because there is no guarances a pointer to the the

INTERNAL REPRESENTATION OF THE STRING DATA; It Could Return A Pointer To

An unmodifiable copy ofthe string ¯S DATA, One T¡ ¯SCORRECTLYFORMAT - TED for a c API. (IF this Makes The Efficiency Hairs on the back of Your

Neck Rise Up Alarm, REST Assured That The Alarm IS Probably False. i

Don¡ ¯T Know of any contemporary library implemementation what take

Advantage of this latitude.)

For a vector, you have a little more flexibility. If you pass v to a c API

That modifies v¡ ¯S Elements, That¡ ¯S TYPICLY OKAY, But The Called Routine

Must not attempt to change the number of elements in the vector. for

Example, IT Must Not Try To. ° Create. ± New Elements in a Vector ¡ ¯S unused

Capacity.if It Does, V Will Become ITNALLY Inconsistent, Because IT

Won¡ ¯T know its correct size ann longer. V.si ze () Will Yield IncorRect

Results. and if the called routine attempts to add data to a vector

Whose size andcapacity (seeitem14) Arethe Same, Truly Horrible

Things could happen. I don¡ ¯ THEEN Want to Contemplate Them. They¡ ¯Re

Just TOO AWFUL.

Did you notice my use of the word ° Typically. ± in the phrase ° That¡ ¯S TYP-ICALLYOKAY. ± in the preceding paragraph? Of course you did. Some Vec-Tors

Have Extra Constraints on Their Data, And if you pass a vector to

An API That Modifies the Vector. ¯S DATA, You Must Ensure That The Addi-Tional

Constraints Continue to Be Satisfied. for Example, Item 23

Explains How Sorted Vectors Can Off Be a Viable Alternative to Asso-Ciative

Containers, But it. ¯S IMPORTANT for Such Vectors to Remain

Sorted. if you pass a sorted vector to an api thing mother modify the vec-tor¡ ¯S

Data, you. ¯LL Need to Take Into Account That The Vector May No

Longer Be sorted after the call has return.

If you have a vector that you hr. ¯D like to initialize with elements from a c

API, You Can Take Advantage Of The Underlying Layout Compatibility of

Vectors andArraysbyPassingtothe Apithe StorageFor Thevector¡ ¯S

Elements:

// c API: this function takes a pointer to an array of at MOST ARRAYSIZE

// Doubles and Writes Data to It. It Returns the Number of Doubles Written,

// Which is never more Than maxnumdoubles.

SIZE_T FILLARRAY (double * parray, size_t arraysize);

Vector VD (MaxNumdouBles); // Create a Vector whose

// size is maxnumdoubles

vd.resize (Fillarray (& VD [0], vd.size ())); // Have Fillarray Write Data

// INTO VD, THEN RESIZE VD

// to the number of

// Elements Fillarray Wrote

THIS TECHNIQUE WORKS ONLY for Vectors, Because ONLY VECTORS AREGUAR-ANTEED

To Have The Same Underlying Memory Layout As Arrays. if you

Want to Initialize A String With Data from a c API, HOWEVER, You Can do ഊ IT Easily Enough. Just Have The API Put The Data Into a Vector ,

THEN COPY THE DATA from the vector to the string:

// c API: This function takes a pointer to an array of at motraysize // Chars and Writes Data to it. It Returns the number of chars Written,

// Which is never more Than maxnumchars.

SIZE_T FILLSTRING (Char * PARRAY, SIZE_T ARRAYSIZE);

Vector vc (maxnumchars); // Create a Vector whose

// size is maxnumchars

Size_t charswritten = FillString (& VC [0], vc.size ()); // Have FillString Write

// INTO VC

String s (vc.begin (), vc.begin () charswritten; // Copy Data from VC to S

// via Range Constructor

// (See Item 5)

IN FACT, THE IDEA of Having a c Api Put Data INTO A Vector and THEN COPY-ING

The Data Into The Stl Container You Really Want IT in Always Works:

SIZE_T FILLARRAY (double * parray, size_t arraysize); // AS Above

Vector VD (MaxNumdouBles); // Also as Above

Vd.resize (Fillarray (& VD [0], vd.size ());

Deque d (vd.begin (), vd.end ()); // Copy Data INTO

// deve

List L (vd.begin (), vd.end ()); // Copy Data Into List

Set s (vd.begin (), vd.end ()); // Copy Data INTO SET

Furthermore, this hints athow stl containers other Than Vector OR

String Can Pass their data to c apis. Just Copy Each Container¡¡ ¯S data

INTO A Vector, THEN Pass It to the API:

Void Dosomething (const INT * PINTS, SIZE_T NUMINTS); // C API (from Above)

Set intSet; // set That Will Hold

... // Data To Pass To API

Vector v (intSet.Begin (), intSet.end ()); // Copy SET DATA INTO

// a Vector

IF (! v.empty ()) DOSMETHING (& V [0], v.size ()); // Pass the data to

// the API

You Could Copy The Data Into An Array, Too, Then Pass the array to the

C API, But Why Would you want to? Unless you know the size of the

Container During Compilation, You. ¯D Have to Allocate the Array Dynam-Ically, And Item 13 Explains Why You Should Prefer Productors to Dynami-Cally

Allocated arrays annily.

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

New Post(0)