Reputation: 23
I'm working on a project for school and I am running into a bit of a problem (error is in the title).
Here is the line of code that runs into the error:
kruskalS[n].nodeList[m].push_back(tempFirstCity);
kruskalS
is a struct and nodeList
is a vector of type string
within the struct and I'm trying to insert tempFirstCity
(also a string
) into that array.
I could easily be making a basic mistake since I haven't done any programming since April. Any kind of help would be appreciated and I'm willing to post a bit more information from the program if needed.
Upvotes: 2
Views: 18000
Reputation: 10756
You say nodeList is an array of type string. i.e. std::string nodeList[x]
where x is a constant.
Then assigning a new element to that array where m < x is as follows:
kruskalS[n].nodeList[m] = tempFirstCity;
For appending to end of vector you don't need the index m:
kruskalS[n].nodeList.push_back(tempFirstCity);
For inserting at index m:
vector<string>::iterator itr = nodeList.begin();
for (int i = 0; i < m; i++)
itr++;
nodeList.insert(itr, tempFirstCity);
Upvotes: 0
Reputation: 72271
A std::string
is (sort of) a container of char
s. A push_back
function is used to add one element to the end of a container. So when you call kruskalS[n].nodeList[m].push_back(tempFirstCity);
, you say you are trying to add one element to the end of the string
called kruskalS[n].nodeList[m]
. So the compiler expects that one element to be a char
.
If you know that tempFirstCity
is not empty and you want to add the first char
from tempFirstCity
to the end of kruskalS[n].nodeList[m]
(including the case where you know tempFirstCity.size() == 1
), you can do
kruskalS[n].nodeList[m].push_back(tempFirstCity[0]);
If you want to add the entire string after any current contents, you can do
kruskalS[n].nodeList[m] += tempFirstCity;
If you expect there are no current contents and/or you want to just replace anything already there with the tempFirstCity
string, you can do
kruskalS[n].nodeList[m] = tempFirstCity;
Upvotes: 5
Reputation: 3633
In C++, you can use string::c_str()
to convert a string to C programming char
array..
Upvotes: -2