Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

CStrings and std::vectors

Status
Not open for further replies.

Kalisto

Programmer
Feb 18, 2003
997
GB
I have (to me) a strange problem.

I have a vector of CStrings
I wish to remove the last String from the vector and add it to another string.

Code:
//Retrieve the last good string
CString &last = ptrVec->back();
//Add to the existing CString object
myString += last;

Simple enough I thought.
If I run the code as above (and step through in debugger) then although last does contain a value, it does not add it to myString.

If I do myString += *last; then it adds the first letter of last to the string.

I have had this issue before, and cant remember how I solved it, so rather than waste anymore time going mad, can anyone else out there hit me with a plank of the blindingly obvious and tell me whats wrong?

Ta.

K




 
Your code looks OK, and should work if
Code:
ptrVec->back() != ptrVec->end();
>I wish to remove the last String

Are you removing it before you do the += assignment, or is the posted code really whats done? Since it is a reference you shouldn't remove it until after the += assignment

Are you sure the ptrVec->back() string isn't empty?

>If I do myString += *last; then it adds the first letter of last to the string.

Yeah, "*last" invokes the (LPCTSTR) operator of the CString, but the "*" then defer it (regular C++ access of pointer content), like:
Code:
  const char* s = "123";   
  char ch = *s; // *s == '1'

At least that indicated the ->back() isn't empty.

Step into the += assignment, and try to figure out what's wrong...

Minor note: If you're not supposed to change the string in the vector I suggest a const declaration:
Code:
const CString &last = ptrVec->back();






/Per
[sub]
"It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure."[/sub]
 
Thanks for the reply Per.

I have done some investigations (But due to time, I have a working Solution, and I have stopped now)

For some Bizzarre reason, the code works if I wrap the CString inside an object.

(The += was the Standard CString Implementation)

As my strings are all a max of 20 chars, I have found that if I have a char[20] array, and strcpy (chararray,ptrVec->back()) that works, and due to time constraints I have had to use that rather than investigate further.

Cheers,

K
 
You could also see if works better with std::string

/Per
[sub]
"It was a work of art, flawless, sublime. A triumph equaled only by its monumental failure."[/sub]
 
Im suspecting it will, but im going to have to leave it for now!
Thanks
K
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top