简体   繁体   中英

Copying vector to std::string

Can anyone explain to me why code below does not work properly ? There is no compiling issues, but output is wrong. I guess problem lies within std::inserter .

Program output :

Expected output: 147497

#include <vector>
#include <string>
#include <algorithm>

int main()
{
  std::vector<char> vec;
  vec.push_back(1);
  vec.push_back(4);
  vec.push_back(7);
  vec.push_back(4);
  vec.push_back(9);
  vec.push_back(7);

  std::string test;

  if (!vec.empty())
  {
    std::copy(vec.begin(),vec.end(),std::inserter(test,std::end(test)));
   }
  std::cout << test;
}

You are inserting non-visual ASCII control characters into your vector. You need to insert visual ASCII characters instead:

// note the use of single quotes!
vec.push_back('1');
vec.push_back('4');
vec.push_back('7');
vec.push_back('4');
vec.push_back('9');
vec.push_back('7');

char(1) has a numeric value of 1. char('1') has a numeric value of 49 in ASCII.

Also, since you are inserting characters into test at the end of the string, consider using std::back_inserter instead of std::inserter (either way, you don't need to test for vec.empty() as standard algorithms work fine with iterator ranges where begin == end ):

std::string test;
std::copy(vec.begin(), vec.end(), std::back_inserter(test));

Or, just use the std::string constructor that takes iterators as input:

std::string test(vec.begin(), vec.end());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM