0

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?

1
  • Curse C++ and its implicit int->char conversions. Something like key += std::to_string(temp.at(i)); might suit you better. Also, "" + temp.at(0) evaluates to a random address, not a string. Commented Oct 29, 2012 at 3:05

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

7 Comments

I don't think compilers issue warnings for implicit int->char conversions.
Actually it seems to depend on the warning level
I get nothing from GCC 4.7.2 or VS11 (both my own with warnings cranked up) with this: liveworkspace.org/code/f12876f52980fd7b67a52fe164ec8408
Have you tried setting the warning level to 4 in Visual Studio?
Indeed I have :/ That implicit conversion is really one we could do without.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.