Re: C++ Primer ex 5.18
On Jul 25, 10:34 am, arnuld <geek.arn...@gmail.com> wrote:
it does not run and even does not even give me any clue to the problem in
its output :(
/* C++ Primer - 4/e
* chapter 5 - Expressions
* exercise 5.18
* STATEMENT
* write a programme that defines a vector of pointers to strings.
read the vector, printing each string and its corresponding size.
*/
#include <iostream>
#include <vector>
#include <string>
int main()
{
std::vector<std::string*> psvec;
std::string input_string;
std::string* ps;
while(std::cin >> input_string)
{
*ps = input_string;
What does ps point to here? Somehow, you're going to have to
get memory to which the pointer can point.
psvec.push_back(ps++);
}
/* printing the strings pointed by the pointers in the vector*/
for(std::vector<std::string*>::const_iterator iter = psvec.begin();
iter != psvec.end(); ++iter)
{
std::cout << "string: " << **iter
<< " size: " << (*iter).size() /* error is here */
What is the type of *iter?
C++ has a moderately strict type system. Whatever *iter
returns, it should have the value type of the array. What type
does the array contain? Is the . operator legal on such types?
What operators might be legal?
<< std::endl;
/* double-defrenced operator because it points to a pointer
rather than a value */
}
/* i was thinking of using "std::copy" from <algorithm> and
"ostream_iterator" from <sstream> from but was not able to
understand the peculiar mechanism of both of them */
You can't use it if you want to output the size as well. (Well,
actually you can, but doing so would require some funny
business, and is probably not a good idea.)
return 0;
}
--
James Kanze (GABI Software) email:james.kanze@gmail.com
Conseils en informatique orient=E9e objet/
Beratung in objektorientierter Datenverarbeitung
9 place S=E9mard, 78210 St.-Cyr-l'=C9cole, France, +33 (0)1 30 23 00 34