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?
The problem seems to be here:
You are trying to append an integer to a string without getting the string representation of the integer first. Try replacing that line with:
If your compiler doesn’t support C++11, try this (don’t forget to
#include <sstream>):Or, if you have the option to use Boost (http://boost.org/ ), try its lexical_cast:
The reason this code compiled in the first place, is because
push_backaccepts acharas its parameter and you’re passing anintwhich gets converted to char (although I would expect a warning from the compiler in this case).P.S.: Same applies for the line