Reputation: 105
I am a student and haven't been taught vectors yet, but I need to use them now. I am trying to make a vector of structs. The struct is a label for assembly code. I resize the vector each time I want to add a label, however, when I try to retrieve the information from the labels, they are all the same. I can't actually share my code unfortunately, but I will show what I think are the lines necessary to help me solve this problem. So, what am I doing wrong? If you need to see more code, let me know.
Declared globally:
vector<Label> labeldir;
Resizing vector and adding information, label is the name of a label in a file of assembly code:
labeldir.resize(labelnum + 1);
labeldir[labelnum].name = label;
Note: it is running in a while loop, labelnum is incrimented each time a label is found.
Example of accessing names of each Label:
for (int i = 0; i < labeldir.size(); i++){
cout << "Label entry " << i << " name : " << labeldir[i].name << endl;
}
The corresponding output, notice the issue (the above code is in a while loop, this is 3 iterations of it):
Label entry 0 name : start
Label entry 0 name : done
Label entry 1 name : done
Label entry 0 name : five
Label entry 1 name : five
Label entry 2 name : five
The first 3 labels in the assembly code, there would be lines between the first and second label but they would be regular instructions.:
start add 1 2 1 decrement reg1
done halt end of program
five .fill 5
Upvotes: 0
Views: 164
Reputation: 532
From the information that you have provided i am assuming that you are having a problem in adding label names to vector labeldir.
whenever you found a label you can add in the following way:
vector<Label> laberdir;
//As you fill the struct label with the name
Label label1;
label1.name = "start";
labeldir.pushback(label1);
labelNum = labelNum + 1;
and as you sad Label is of struct type as
struct Label
{
std::string name;
};
Upvotes: 0
Reputation: 490663
I'd almost bet that the name
member of your Label
structure is a char *
. That means instead of creating a separate string for each label, you're only creating separate pointers -- but they're all pointing to the same place.
When you try to print out your contents, they're all pointing to the same buffer, so every Label shows the name most recently read into that buffer.
Cure: use std::string
instead of char *
.
Upvotes: 2
Reputation: 2985
It's a bit hard to see exactly what you're doing wrong but let me have a guess:
Your code to load up your vector should probably look like this:
#include <string>
struct Label
{
Label(const std::string& N) : Name(N)
{}
Label()
{}
std::string Name;
};
int main()
{
std::vector<Label> labeldir;
labeldir.push_back(Label("one"));
labeldir.push_back(Label("two"));
labeldir.push_back(Label("three"));
labeldir.push_back(Label("four"));
int i = 0;
for(auto l : labeldir)
{
std::cout << "Label entry " << i++ << " name : " << l.Name << "\n";
}
system("PAUSE");
return 0;
}
Upvotes: 2