Reputation: 11
I am a newbie, I have a problem which trouble me a lot. Please help me out.
I am trying to save char array values in a vector. The size of the vector is the same as the number I push_back. However, all the values in the vector is the last value I push_back.
Here are the code:
vector<char*> qField;
int index = 0;
for (int i =1;i <=q_size-seedLength;i++)
{
index++;
for (int j=0;j<seedLength-1;j++)
{
seed[j] = seed[j+1];
}
seed[seedLength-1] = *q_ptr;
++q_ptr;
seed[seedLength] = '\0';
qField.push_back(seed);
cout << "Insert Seed"<<index<<"\t\t: " <<qField[i]<<"\n";
}
/*
for (int x=0; x<qField.size();x++)
{
cout << " Result Query"<<x<<": " << qField[x]<<"\n";
}
*/
int x = 0;
for(nuc_vector::iterator iter=qField.begin();iter!=qField.end();++iter)
{
cout << x <<"\n";
x++;
cout << "Query " << *iter<<"\n";
}
The strange thing is that the value seems to be stored in the vector right after the push_back. However, when I use another loop to output all the values in the vector qField, all the values are same as the last value pushed back.
Here are part of my results:
Insert Seed7313 : 00133310
Insert Seed7314 : 01333100
Insert Seed7315 : 13331001
Insert Seed7316 : 33310013
Insert Seed7317 : 33100130
Insert Seed7318 : 31001303
Insert Seed7319 : 10013033
0
Query 10013033
1
Query 10013033
2
Query 10013033
3
Query 10013033
4
Query 10013033
5
Query 10013033
6
Query 10013033
Why is that ? Is there any thing wrong.
Upvotes: 0
Views: 1960
Reputation: 101
Try by wrapping seed inside a std::string. Just few lines of code should be changed:
#include<string>
vector<std::string> qField;
...
...
qField.push_back(std::string(seed));
Upvotes: 1
Reputation: 385194
It didn't.
A char*
is not a string, or a container, or anything like that. It's not the "value" that you think it is. It is a pointer. It is an object that points to something else: in this case, apparently, a buffer of char
s.
Your vector qField
contains copies of the same pointer (seed
), over and over again. So yes of course when you dereference each copy, the result will be the same! Even though you modified the thing that the pointer points to in the meantime.
Copying a pointer does not magically copy the thing it points to then update the pointer's value to now point to the new copy of the pointee.
You want an object that semantically contains the data you're trying to store. You want it to have value semantics.
You want to store std::string
s instead.
std::vector<std::string> qField;
Upvotes: 11