Reputation: 6181
So I have a function, where KaylesPosition
is a class with a vector<int>
called piles
:
// Produces a key to compare itself to equivalent positions
std::string KaylesPosition::makeKey(){
std::vector<int> temp(piles.size());
for (int i = 0;i<piles.size();i++){
temp[i]=piles[i];
}
std::sort (temp.begin(),temp.end());
std::string key = "" + temp.at(0);
for (int i=1 ; i<temp.size() ; i++){
key.push_back('.');
key.push_back(temp.at(i));
}
return key;
}
My expected output should be all of the elements in piles
in order, separated by periods. However instead, I get key
return as "_M_range_check". I have tried this using std::string.append() and I get either an empty string or a period. How do I get this function to return a string of all of the values in piles
as expected?
Upvotes: 0
Views: 88
Reputation:
The problem seems to be here:
key.push_back(temp.at(i));
You are trying to append an integer to a string without getting the string representation of the integer first. Try replacing that line with:
key += std::to_string(temp.at(i)); // This will only work if your compiler supports C++11
If your compiler doesn't support C++11, try this (don't forget to #include <sstream>
):
std::ostringstream o;
o << temp.at(i);
key += o.str();
Or, if you have the option to use Boost (http://boost.org/ ), try its lexical_cast:
key += boost::lexical_cast<std::string>(temp.at(i));
The reason this code compiled in the first place, is because push_back
accepts a char
as its parameter and you're passing an int
which gets converted to char (although I would expect a warning from the compiler in this case).
P.S.: Same applies for the line
std::string key = "" + temp.at(0);
Upvotes: 1