inserting the string pointer in the vector and displaying the value

Feb 8, 2012 at 5:22pm
Hi All ,
I have problem with the code as , i am trying to insert the string in the vector
i am getting errors .. as i am getting the error in inserting the vaule in the vector i stopped ...for displaying the value in the vector . This is my code .

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <string>
#include <vector>
using namespace std ; 

int main ()
{
  vector<string*> vect; 
  vect->pushback("Jill");
  vect->pushback("Jane");
  vect->pushback("Rosy");

   return 0 ; 
}


please consider that i have to use string pointer in the vector .
I have google the topic but came up with nothing .

Thanks
xxx
Feb 8, 2012 at 5:30pm
vector<string*> vect;
This makes a std::vector of pointers to std::string.

vect->pushback("Jill");
"vect" itself is not a pointer, so you should be treating it as such.

pushback("Jill");
Pointers to std::string (and pointers in general) do not have any constructors which take a const char *, except for const char * themselves.
Feb 8, 2012 at 5:38pm
Thanks LB ... but
Pointers to std::string (and pointers in general) do not have any constructors which take a const char *, except for const char * themselves.


I am not getting this line .
do you mean something like this .
1
2
3
4
5
6
vector<string*> vect ; 

string str = "Jill" ; 
string str1 = "Rosy"; 
vect.pushback(&str);
vect.pushback(&str1);

Is this the right way
Last edited on Feb 8, 2012 at 5:38pm
Feb 8, 2012 at 6:16pm


display of the value stored in the vector is

1
2
3
4
5
6
vector<string*>::iterator it ;
        for( it = vect.begin() ; it != vect.end() ; it++)
        {
                display_str = *it ;
                cout<<"\n The string = " << display_str;
        }


it is throwing the error i dont know why ..
Feb 8, 2012 at 6:34pm
What exactly is the error? I'm guessing you are pushing a temporary address into your vector and when you try to dereference the pointer... Boom.
Feb 8, 2012 at 6:37pm
i have to use string pointer in the vector
¿why?
it is throwing the error i dont know why
¿what error?
Feb 8, 2012 at 9:27pm
Dereferencing the iterator returns a pointer to a std::string. You need to dereference that too:
**it
Feb 10, 2012 at 7:35pm
Hi m
thanks LB it worked ..
Topic archived. No new replies allowed.