I’m trying to parse the lines of a text file and then store them inside of a vector<string>. I’m coming from a Java background and am confused on how C++ handles assigning stuff to the value of a buffer. Here is my code:
string line;
vector<string> adsList;
ifstream inputFile;
inputFile.open("test.txt");
while(getline(inputFile, line))
{
adsList.push_back(line);
}
In Java, when adding to a data structure a copy of the object is made and then that copy is inserted. In C++, my understanding is that the data structures only hold references so that any operation is very fast. What is the proper way to achieve what I want to do in C++? I have also tried the following code:
vector<string> adsList;
string line;
ifstream inputFile;
inputFile.open("test.txt");
while(getline(inputFile, line))
{
string *temp = new string;
*temp = line;
adsList.push_back(*temp);
}
With my reasoning here being that creating a new string object and storing that would preserve it after being destroyed each loop iteration. C++ seems to handle this completely opposite of Java and I am having a hard time wrapping my head around it.
edit: here is what test.txt looks like:
item1 item1 item1
item2 item2 item2
item3 item3 item3
item4 item4 item4
I’m trying to store each line as a string and then store the string inside my vector. So the front of the vector would have a string with value “item1 item1 item1”.
push_back()makes a copy, so your first code sample does exactly what you want it to do. In fact, all C++ structures store copies by default. You’d have to have a container of pointers to not get copies.