我有一个 std::vector<custom_class>
我想加入一个逗号分隔的字符串。
我找到了代码:
std::stringstream s;
std::string delimeter = ",";
copy(v.begin(), v.end(), std::ostream_iterator<int>(s, delimeter.c_str()));
这非常适合连接单一类型的 vector ,例如 int
.但是,我想仅加入我的custom_class
的某个属性。 .
我可以使用 copy
吗?仅复制并加入我的 custom_class
的某个属性?
例如,我的 vector<custom_class>
看起来像:
v[0].A = 1
v[0].B = 2
v[0].C = 3
v[1].A = 1
v[1].B = 2
v[1].C = 3
v[2].A = 1
v[2].B = 2
v[2].C = 3
v[3].A = 1
v[3].B = 2
v[3].C = 3
我想使用 std::copy
只加入属性的那些值 B
(作为示例)返回值:
2,2,2,2
如果不循环遍历 v
是否可能发生这样的事情?明确?
最佳答案
您可以使用标准算法 std::transform
而不是算法 std::copy
例如
std::transform( v.begin(), v.end(), std::ostream_iterator<int>( s, "," ),
[]( const custom_class &c ) { return c.B; } );
另一种方法是使用算法 std::accumulate
在 header 中声明 <numeric>
和功能std::to_string
例如
std::string s = std::accumulate( v.begin(), v.end(), std::string(),
[]( std::string &s, const custom_class &c )
{
return ( s += std::to_string( c.B ) + ',' );
} );
关于C++ - 将 vector<custom_class> 的属性连接到字符串中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24745243/