문제
나는 vector<int>
정수가 포함된 컨테이너(예:{1,2,3,4}) 다음 형식의 문자열로 변환하고 싶습니다.
"1,2,3,4"
C++에서 이를 수행하는 가장 깨끗한 방법은 무엇입니까?Python에서는 다음과 같이 합니다.
>>> array = [1,2,3,4]
>>> ",".join(map(str,array))
'1,2,3,4'
해결책
확실히 파이썬만큼 우아하지는 않지만 C ++의 파이썬만큼 우아하지는 않습니다.
당신은 a를 사용할 수 있습니다 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
대신에.
다른 팁
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=',';
});
}
보다 이 질문 나는 작은 수업을 위해 썼다. 이것은 후행 쉼표를 인쇄하지 않습니다. 또한 C ++ 14가 다음과 같은 알고리즘의 범위 기반 등가물을 계속 제공한다고 가정하면
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
}
std :: 축적을 사용할 수 있습니다. 다음 예를 고려하십시오
if (v.empty()
return std::string();
std::string s = std::accumulate(v.begin()+1, v.end(), std::to_string(v[0]),
[](const std::string& a, int b){
return a + ',' + std::to_string(b);
});
또 다른 대안은 사용입니다 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);
또한 파이썬만큼 좋지는 않습니다. 이를 위해 나는 a를 만들었습니다 join
기능:
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(","));
내가 왜 반복자를 통과했는지 물어볼 수 있습니다. 글쎄, 실제로 배열을 뒤집고 싶었으므로 다음과 같이 사용했습니다.
std::string s=join(array.rbegin(), array.rend(), std::string(","));
이상적으로는 숯 유형을 추론하고 문자열 스트림을 사용할 수있는 지점까지 템플릿을 만들고 싶습니다. 그러나 아직 알 수 없었습니다.
Boost와 C++11을 사용하면 다음과 같이 달성할 수 있습니다.
auto array = {1,2,3,4};
join(array | transformed(tostr), ",");
글쎄, 거의.전체 예는 다음과 같습니다.
#include <array>
#include <iostream>
#include <boost/algorithm/string/join.hpp>
#include <boost/range/adaptor/transformed.hpp>
int main() {
using boost::algorithm::join;
using boost::adaptors::transformed;
auto tostr = static_cast<std::string(*)(int)>(std::to_string);
auto array = {1,2,3,4};
std::cout << join(array | transformed(tostr), ",") << std::endl;
return 0;
}
신용 법무관.
다음과 같이 모든 값 유형을 처리할 수 있습니다.
template<class Container>
std::string join(Container const & container, std::string delimiter) {
using boost::algorithm::join;
using boost::adaptors::transformed;
using value_type = typename Container::value_type;
auto tostr = static_cast<std::string(*)(value_type)>(std::to_string);
return join(container | transformed(tostr), delimiter);
};
이것은 단지 주어진 수수께끼를 해결하려는 시도입니다. 1800 정보의 발언 그의 두 번째 솔루션에서는 일반성이 부족한 문제에 대한 질문에 대답하려는 시도가 아닙니다.
template <class Str, class It>
Str join(It begin, const It end, const Str &sep)
{
typedef typename Str::value_type char_type;
typedef typename Str::traits_type traits_type;
typedef typename Str::allocator_type allocator_type;
typedef std::basic_ostringstream<char_type,traits_type,allocator_type>
ostringstream_type;
ostringstream_type result;
if(begin!=end)
result << *begin++;
while(begin!=end) {
result << sep;
result << *begin++;
}
return result.str();
}
내 컴퓨터 (TM)에서 작동합니다.
많은 템플릿/아이디어. 광산은 일반적이거나 효율적이지는 않지만, 나는 단지 같은 문제를 겪었고 이것을 짧고 달콤한 것으로 믹스에 던지기를 원했습니다. 가장 짧은 줄에서 승리합니다 ... :)
std::stringstream joinedValues;
for (auto value: array)
{
joinedValues << value << ",";
}
//Strip off the trailing comma
std::string result = joinedValues.str().substr(0,joinedValues.str().size()-1);
당신이하고 싶다면 std::cout << join(myVector, ",") << std::endl;
, 당신은 다음과 같은 일을 할 수 있습니다.
template <typename C, typename T> class MyJoiner
{
C &c;
T &s;
MyJoiner(C &&container, T&& sep) : c(std::forward<C>(container)), s(std::forward<T>(sep)) {}
public:
template<typename C, typename T> friend std::ostream& operator<<(std::ostream &o, MyJoiner<C, T> const &mj);
template<typename C, typename T> friend MyJoiner<C, T> join(C &&container, T&& sep);
};
template<typename C, typename T> std::ostream& operator<<(std::ostream &o, MyJoiner<C, T> const &mj)
{
auto i = mj.c.begin();
if (i != mj.c.end())
{
o << *i++;
while (i != mj.c.end())
{
o << mj.s << *i++;
}
}
return o;
}
template<typename C, typename T> MyJoiner<C, T> join(C &&container, T&& sep)
{
return MyJoiner<C, T>(std::forward<C>(container), std::forward<T>(sep));
}
이 솔루션은 보조 버퍼를 만들지 않고 출력 스트림에 직접 조인하고 오퍼레이터 << 타조에 <<이있는 모든 유형과 함께 작동합니다.
이것은 또한 어디에서 작동합니다 boost::algorithm::join()
당신이있을 때 실패합니다 vector<char*>
대신 a vector<string>
.
나는 1800 년대의 대답을 좋아한다. 그러나 IF 문의 결과는 첫 번째 반복 후 한 번만 변경되므로 첫 번째 반복을 루프에서 옮길 것입니다.
template <class T, class A>
T join(const A &begin, const A &end, const T &t)
{
T result;
A it = begin;
if (it != end)
{
result.append(*it);
++it;
}
for( ;
it!=end;
++it)
{
result.append(t);
result.append(*it);
}
return result;
}
이것은 당신이 원한다면 물론 더 적은 수의 진술로 줄일 수 있습니다.
template <class T, class A>
T join(const A &begin, const A &end, const T &t)
{
T result;
A it = begin;
if (it != end)
result.append(*it++);
for( ; it!=end; ++it)
result.append(t).append(*it);
return result;
}
문제에 대한 우아한 해결책을 제공하려는 흥미로운 시도가 있습니다. 템플릿 스트림을 사용하여 OP의 원래 딜레마에 효과적으로 답변하는 아이디어가있었습니다. 이것은 오래된 게시물이지만, 나는 이것을 우연히 발견하는 미래의 사용자들이 내 솔루션이 유익하다는 것을 알기를 바라고 있습니다.
첫째, 일부 답변 (허용 된 답변 포함)은 재사용 성을 촉진하지 않습니다. C ++는 표준 라이브러리에서 문자열에 가입하는 우아한 방법을 제공하지 않기 때문에 (내가 본) 유연하고 재사용 할 수있는 문자열을 만드는 것이 중요합니다. 여기에 내 사진이 있습니다.
// Replace with your namespace //
namespace my {
// Templated join which can be used on any combination of streams, iterators and base types //
template <typename TStream, typename TIter, typename TSeperator>
TStream& join(TStream& stream, TIter begin, TIter end, TSeperator seperator) {
// A flag which, when true, has next iteration prepend our seperator to the stream //
bool sep = false;
// Begin iterating through our list //
for (TIter i = begin; i != end; ++i) {
// If we need to prepend a seperator, do it //
if (sep) stream << seperator;
// Stream the next value held by our iterator //
stream << *i;
// Flag that next loops needs a seperator //
sep = true;
}
// As a convenience, we return a reference to the passed stream //
return stream;
}
}
이제 이것을 사용하려면 다음과 같은 일을 할 수 있습니다.
// Load some data //
std::vector<int> params;
params.push_back(1);
params.push_back(2);
params.push_back(3);
params.push_back(4);
// Store and print our results to standard out //
std::stringstream param_stream;
std::cout << my::join(param_stream, params.begin(), params.end(), ",").str() << std::endl;
// A quick and dirty way to print directly to standard out //
my::join(std::cout, params.begin(), params.end(), ",") << std::endl;
스트림을 사용하면 결과가 나중에 회수 할 수있는 문자열 스트림에 결과를 저장하거나 스트림으로 구현 된 네트워크 연결에 직접 쓸 수 있기 때문에이 솔루션을 매우 유연하게 만드는 방법에 유의하십시오. 인쇄되는 유형은 단순히 반복 가능하고 소스 스트림과 호환되어야합니다. STL은 다양한 유형과 호환되는 다양한 스트림을 제공합니다. 그래서 당신은 정말로 이것으로 마을에 갈 수 있습니다. 내 머리 꼭대기에서 벡터는 int, float, double, string, unsigned int, someobject*등일 수 있습니다.
string s;
for (auto i : v)
s += (s.empty() ? "" : ",") + to_string(i);
확장 된 조인 지원을 추가하기 위해 헬퍼 헤더 파일을 만들었습니다.
아래 코드를 일반 헤더 파일에 추가하고 필요할 때 포함하십시오.
사용 예제 :
/* An example for a mapping function. */
ostream&
map_numbers(ostream& os, const void* payload, generic_primitive data)
{
static string names[] = {"Zero", "One", "Two", "Three", "Four"};
os << names[data.as_int];
const string* post = reinterpret_cast<const string*>(payload);
if (post) {
os << " " << *post;
}
return os;
}
int main() {
int arr[] = {0,1,2,3,4};
vector<int> vec(arr, arr + 5);
cout << vec << endl; /* Outputs: '0 1 2 3 4' */
cout << join(vec.begin(), vec.end()) << endl; /* Outputs: '0 1 2 3 4' */
cout << join(vec.begin(), vec.begin() + 2) << endl; /* Outputs: '0 1 2' */
cout << join(vec.begin(), vec.end(), ", ") << endl; /* Outputs: '0, 1, 2, 3, 4' */
cout << join(vec.begin(), vec.end(), ", ", map_numbers) << endl; /* Outputs: 'Zero, One, Two, Three, Four' */
string post = "Mississippi";
cout << join(vec.begin() + 1, vec.end(), ", ", map_numbers, &post) << endl; /* Outputs: 'One Mississippi, Two mississippi, Three mississippi, Four mississippi' */
return 0;
}
현장 뒤의 코드 :
#include <iostream>
#include <vector>
#include <list>
#include <set>
#include <unordered_set>
using namespace std;
#define GENERIC_PRIMITIVE_CLASS_BUILDER(T) generic_primitive(const T& v) { value.as_##T = v; }
#define GENERIC_PRIMITIVE_TYPE_BUILDER(T) T as_##T;
typedef void* ptr;
/** A union that could contain a primitive or void*,
* used for generic function pointers.
* TODO: add more primitive types as needed.
*/
struct generic_primitive {
GENERIC_PRIMITIVE_CLASS_BUILDER(int);
GENERIC_PRIMITIVE_CLASS_BUILDER(ptr);
union {
GENERIC_PRIMITIVE_TYPE_BUILDER(int);
GENERIC_PRIMITIVE_TYPE_BUILDER(ptr);
};
};
typedef ostream& (*mapping_funct_t)(ostream&, const void*, generic_primitive);
template<typename T>
class Join {
public:
Join(const T& begin, const T& end,
const string& separator = " ",
mapping_funct_t mapping = 0,
const void* payload = 0):
m_begin(begin),
m_end(end),
m_separator(separator),
m_mapping(mapping),
m_payload(payload) {}
ostream&
apply(ostream& os) const
{
T begin = m_begin;
T end = m_end;
if (begin != end)
if (m_mapping) {
m_mapping(os, m_payload, *begin++);
} else {
os << *begin++;
}
while (begin != end) {
os << m_separator;
if (m_mapping) {
m_mapping(os, m_payload, *begin++);
} else {
os << *begin++;
}
}
return os;
}
private:
const T& m_begin;
const T& m_end;
const string m_separator;
const mapping_funct_t m_mapping;
const void* m_payload;
};
template <typename T>
Join<T>
join(const T& begin, const T& end,
const string& separator = " ",
ostream& (*mapping)(ostream&, const void*, generic_primitive) = 0,
const void* payload = 0)
{
return Join<T>(begin, end, separator, mapping, payload);
}
template<typename T>
ostream&
operator<<(ostream& os, const vector<T>& vec) {
return join(vec.begin(), vec.end()).apply(os);
}
template<typename T>
ostream&
operator<<(ostream& os, const list<T>& lst) {
return join(lst.begin(), lst.end()).apply(os);
}
template<typename T>
ostream&
operator<<(ostream& os, const set<T>& s) {
return join(s.begin(), s.end()).apply(os);
}
template<typename T>
ostream&
operator<<(ostream& os, const Join<T>& vec) {
return vec.apply(os);
}
다음은 일반 C ++ 11 솔루션이 있습니다.
int main() {
vector<int> v {1,2,3};
cout << join(v, ", ") << endl;
string s = join(v, '+').str();
}
코드는 다음과 같습니다.
template<typename Iterable, typename Sep>
class Joiner {
const Iterable& i_;
const Sep& s_;
public:
Joiner(const Iterable& i, const Sep& s) : i_(i), s_(s) {}
std::string str() const {std::stringstream ss; ss << *this; return ss.str();}
template<typename I, typename S> friend std::ostream& operator<< (std::ostream& os, const Joiner<I,S>& j);
};
template<typename I, typename S>
std::ostream& operator<< (std::ostream& os, const Joiner<I,S>& j) {
auto elem = j.i_.begin();
if (elem != j.i_.end()) {
os << *elem;
++elem;
while (elem != j.i_.end()) {
os << j.s_ << *elem;
++elem;
}
}
return os;
}
template<typename I, typename S>
inline Joiner<I,S> join(const I& i, const S& s) {return Joiner<I,S>(i, s);}
다음은 요소를 vector
a string
:
std::string join(const std::vector<int>& numbers, const std::string& delimiter = ",") {
std::ostringstream result;
for (const auto number : numbers) {
if (result.tellp() > 0) { // not first round
result << delimiter;
}
result << number;
}
return result.str();
}
당신은 필요합니다 #include <sstream>
~을 위한 ostringstream
.
@SBI의 시도에 대한 확장 a 일반 솔루션 그것은 제한되지 않습니다 std::vector<int>
또는 특정 반환 문자열 유형. 아래에 제시된 코드는 다음과 같이 사용할 수 있습니다.
std::vector<int> vec{ 1, 2, 3 };
// Call modern range-based overload.
auto str = join( vec, "," );
auto wideStr = join( vec, L"," );
// Call old-school iterator-based overload.
auto str = join( vec.begin(), vec.end(), "," );
auto wideStr = join( vec.begin(), vec.end(), L"," );
원래 코드에서, 템플릿 인수 공제는 분리기가 문자열 문자 인 경우 (위의 샘플에서와 같이) 올바른 반환 문자열 유형을 생성하는 데 작동하지 않습니다. 이 경우 typedefs가 좋아요 Str::value_type
함수에서 본문이 올바르지 않습니다. 코드는이를 가정합니다 Str
항상 유형입니다 std::basic_string
, 그래서 그것은 문자열 리터럴에 분명히 실패합니다.
이 문제를 해결하기 위해 다음 코드는 캐릭터 분리기 인수에서 입력하고이를 사용하여 기본 반환 문자열 유형을 생성합니다. 이것은 사용됩니다 boost::range_value
, 주어진에서 요소 유형을 추출합니다 범위 유형.
#include <string>
#include <sstream>
#include <boost/range.hpp>
template< class Sep, class Str = std::basic_string< typename boost::range_value< Sep >::type >, class InputIt >
Str join( InputIt first, const InputIt last, const Sep& sep )
{
using char_type = typename Str::value_type;
using traits_type = typename Str::traits_type;
using allocator_type = typename Str::allocator_type;
using ostringstream_type = std::basic_ostringstream< char_type, traits_type, allocator_type >;
ostringstream_type result;
if( first != last )
{
result << *first++;
}
while( first != last )
{
result << sep << *first++;
}
return result.str();
}
이제 반복기 기반 오버로드로 간단하게 전달되는 범위 기반 오버로드를 쉽게 제공 할 수 있습니다.
template <class Sep, class Str = std::basic_string< typename boost::range_value<Sep>::type >, class InputRange>
Str join( const InputRange &input, const Sep &sep )
{
// Include the standard begin() and end() in the overload set for ADL. This makes the
// function work for standard types (including arrays), aswell as any custom types
// that have begin() and end() member functions or overloads of the standalone functions.
using std::begin; using std::end;
// Call iterator-based overload.
return join( begin(input), end(input), sep );
}
@capone처럼
std::string join(const std::vector<std::string> &str_list ,
const std::string &delim=" ")
{
if(str_list.size() == 0) return "" ;
return std::accumulate( str_list.cbegin() + 1,
str_list.cend(),
str_list.at(0) ,
[&delim](const std::string &a , const std::string &b)
{
return a + delim + b ;
} ) ;
}
template <typename ST , typename TT>
std::vector<TT> map(TT (*op)(ST) , const vector<ST> &ori_vec)
{
vector<TT> rst ;
std::transform(ori_vec.cbegin() ,
ori_vec.cend() , back_inserter(rst) ,
[&op](const ST& val){ return op(val) ;} ) ;
return rst ;
}
그런 다음 다음과 같이 호출 할 수 있습니다.
int main(int argc , char *argv[])
{
vector<int> int_vec = {1,2,3,4} ;
vector<string> str_vec = map<int,string>(to_string, int_vec) ;
cout << join(str_vec) << endl ;
return 0 ;
}
파이썬처럼 :
>>> " ".join( map(str, [1,2,3,4]) )
나는 이런 것을 사용합니다
namespace std
{
// for strings join
string to_string( string value )
{
return value;
}
} // namespace std
namespace // anonymous
{
template< typename T >
std::string join( const std::vector<T>& values, char delimiter )
{
std::string result;
for( typename std::vector<T>::size_type idx = 0; idx < values.size(); ++idx )
{
if( idx != 0 )
result += delimiter;
result += std::to_string( values[idx] );
}
return result;
}
} // namespace anonymous
나는 @sbi의 답변으로 시작했지만 대부분의 시간은 결과 문자열을 스트림에 배관하게되었으므로 메모리에서 전체 문자열을 생성하는 오버 헤드없이 스트림에 배관 할 수있는 아래 솔루션을 만들었습니다.
다음과 같이 사용됩니다.
#include "string_join.h"
#include <iostream>
#include <vector>
int main()
{
std::vector<int> v = { 1, 2, 3, 4 };
// String version
std::string str = join(v, std::string(", "));
std::cout << str << std::endl;
// Directly piped to stream version
std::cout << join(v, std::string(", ")) << std::endl;
}
여기서 String_join.h는 다음과 같습니다.
#pragma once
#include <iterator>
#include <sstream>
template<typename Str, typename It>
class joined_strings
{
private:
const It begin, end;
Str sep;
public:
typedef typename Str::value_type char_type;
typedef typename Str::traits_type traits_type;
typedef typename Str::allocator_type allocator_type;
private:
typedef std::basic_ostringstream<char_type, traits_type, allocator_type>
ostringstream_type;
public:
joined_strings(It begin, const It end, const Str &sep)
: begin(begin), end(end), sep(sep)
{
}
operator Str() const
{
ostringstream_type result;
result << *this;
return result.str();
}
template<typename ostream_type>
friend ostream_type& operator<<(
ostream_type &ostr, const joined_strings<Str, It> &joined)
{
It it = joined.begin;
if(it!=joined.end)
ostr << *it;
for(++it; it!=joined.end; ++it)
ostr << joined.sep << *it;
return ostr;
}
};
template<typename Str, typename It>
inline joined_strings<Str, It> join(It begin, const It end, const Str &sep)
{
return joined_strings<Str, It>(begin, end, sep);
}
template<typename Str, typename Container>
inline joined_strings<Str, typename Container::const_iterator> join(
Container container, const Str &sep)
{
return join(container.cbegin(), container.cend(), sep);
}
다음 코드를 썼습니다. C# String.join을 기반으로합니다. std :: string 및 std :: wstring 및 많은 유형의 벡터와 함께 작동합니다. (의견의 예)
다음과 같이 부릅니다.
std::vector<int> vVectorOfIds = {1, 2, 3, 4, 5};
std::wstring wstrStringForSQLIn = Join(vVectorOfIds, L',');
암호:
// Generic Join template (mimics string.Join() from C#)
// Written by RandomGuy (stackoverflow) 09-01-2017
// Based on Brian R. Bondy anwser here:
// http://stackoverflow.com/questions/1430757/c-vector-to-string
// Works with char, wchar_t, std::string and std::wstring delimiters
// Also works with a different types of vectors like ints, floats, longs
template<typename T, typename D>
auto Join(const std::vector<T> &vToMerge, const D &delimiter)
{
// We use std::conditional to get the correct type for the stringstream (char or wchar_t)
// stringstream = basic_stringstream<char>, wstringstream = basic_stringstream<wchar_t>
using strType =
std::conditional<
std::is_same<D, std::string>::value,
char,
std::conditional<
std::is_same<D, char>::value,
char,
wchar_t
>::type
>::type;
std::basic_stringstream<strType> ss;
for (size_t i = 0; i < vToMerge.size(); ++i)
{
if (i != 0)
ss << delimiter;
ss << vToMerge[i];
}
return ss.str();
}