【发布时间】:2015-03-29 22:48:49
【问题描述】:
我想从 char 数组的开头提取一系列元素并将它们放入字符串中。范围可能小于或等于元素的数量。
这是我想出来的。
// buffer is a std::array<char, 128>
std::string message;
for (int i = 0; i < numberToExtract; ++i)
{
message += buffer.at(i);
}
有没有更好的方法来做到这一点?
我一直在研究类似 std::string 的迭代器构造函数。例如。 std::string(buffer.begin(), buffer.end()) 但我不想要所有元素。
谢谢。
【问题讨论】:
-
使用 STL 时,询问初始化对象的循环通常是个好主意。
-
@Wolf It's not the STL.
-
@Barry I see。我将其改写为注意用 for 循环初始化的 C++ 标准容器。
-
@Wolf 你什么意思?
-
我的意思是这个模式:
{1} container declaration (default construction) {2} for loop consisting in {3} append item to container。这里std::string是容器:您希望它包含提取的字符;这样做,您将失去将其设为 const 的选项,因为您必须将其声明为变量。我经常寻找这种不良副作用的替代品。
标签: c++ arrays string c++11 stdarray