第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將vector <int>轉(zhuǎn)換為字符串

將vector <int>轉(zhuǎn)換為字符串

C++
元芳怎么了 2019-10-28 18:43:29
我有一個vector<int>帶有整數(shù)的容器(例如{1,2,3,4}),我想轉(zhuǎn)換為以下形式的字符串"1,2,3,4"在C ++中最干凈的方法是什么?在Python中,這就是我的操作方式:>>> array = [1,2,3,4]>>> ",".join(map(str,array))'1,2,3,4'
查看完整描述

3 回答

?
牛魔王的故事

TA貢獻1830條經(jīng)驗 獲得超3個贊

絕對不如Python優(yōu)雅,但沒有什么比C ++中的Python優(yōu)雅。


您可以使用stringstream...


std::stringstream ss;

for(size_t i = 0; i < v.size(); ++i)

{

  if(i != 0)

    ss << ",";

  ss << v[i];

}

std::string s = ss.str();

您也可以std::for_each代替使用。


查看完整回答
反對 回復(fù) 2019-10-28
?
湖上湖

TA貢獻2003條經(jīng)驗 獲得超2個贊

使用std :: for_each和lambda可以做一些有趣的事情。


#include <iostream>

#include <sstream>


int main()

{

     int  array[] = {1,2,3,4};

     std::for_each(std::begin(array), std::end(array),

                   [&std::cout, sep=' '](int x) mutable {

                       out << sep << x; sep=',';

                   });

}

請參閱我寫的一堂小課的這個問題。這不會打印結(jié)尾的逗號。同樣,如果我們假設(shè)C ++ 14將繼續(xù)為我們提供基于范圍的等效算法,如下所示:


namespace std {

   // I am assuming something like this in the C++14 standard

   // I have no idea if this is correct but it should be trivial to write if it  does not appear.

   template<typename C, typename I>

   void copy(C const& container, I outputIter) {copy(begin(container), end(container), outputIter);}

}

using POI = PrefexOutputIterator;   

int main()

{

     int  array[] = {1,2,3,4};

     std::copy(array, POI(std::cout, ","));

  // ",".join(map(str,array))               // closer

}


查看完整回答
反對 回復(fù) 2019-10-28
?
慕村225694

TA貢獻1880條經(jīng)驗 獲得超4個贊

另一種選擇是使用std::copy和ostream_iterator類:


#include <iterator>  // ostream_iterator

#include <sstream>   // ostringstream

#include <algorithm> // copy


std::ostringstream stream;

std::copy(array.begin(), array.end(), std::ostream_iterator<>(stream));

std::string s=stream.str();

s.erase(s.length()-1);

還不如Python好。為此,我創(chuàng)建了一個join函數(shù):


template <class T, class A>

T join(const A &begin, const A &end, const T &t)

{

  T result;

  for (A it=begin;

       it!=end;

       it++)

  {

    if (!result.empty())

      result.append(t);

    result.append(*it);

  }

  return result;

}

然后像這樣使用它:


std::string s=join(array.begin(), array.end(), std::string(","));

您可能會問為什么我傳遞了迭代器。好吧,實際上我想反轉(zhuǎn)數(shù)組,所以我這樣使用它:


std::string s=join(array.rbegin(), array.rend(), std::string(","));

理想情況下,我想模板化到可以推斷char類型并使用字符串流的地步,但是我還不能弄清楚。


查看完整回答
反對 回復(fù) 2019-10-28
  • 3 回答
  • 0 關(guān)注
  • 2912 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學(xué)習(xí)伙伴

公眾號

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號