用"*"(特殊字符)初始化向量,然后打印出来
Initialize a vector with '*'(special character) and then print it
我想用特殊字符初始化一个向量,然后打印出来
这是我正在使用的代码
#include <vector>
using namespace std;
int main()
{
std::vector<char> p { *,*,*,*,*,*,* };
for( std::vector<char>::const_iterator i = p.begin(); i != p.end(); ++i)
std::cout << *i << ' ';
}
我知道我错过了一些东西,但就是想不通是什么。我将不胜感激一些建议
std::vector<char> p(7, '*');
对我来说是最自然的。
还有
std::fill_n(back_inserter(p), 7, '*');
@sehe 出色答案的替代方法是使用 string
而不是vector
:
std::string p = "*******";
如果可能的话,我也会使用基于范围的 for 循环:
for (auto ch : p)
std::cout << ch << ' ';
如果你不能使用它,我通常更喜欢std::copy
,比如:
std::copy(p.begin(), p.end(), std::ostream_iterator<char>(std::cout, " "));
可以将版本与初始值设定项列表一起使用:
std::vector<char> p { '*','*','*','*','*','*','*' };
或者,您可以使用构造函数:
std::vector<char> p(7, '*');
见 http://en.cppreference.com/w/cpp/container/vector/vector
相关文章:
- 我编写了以下代码来读取C++矩阵,然后打印其行和列.我收到此错误
- 读取一组用户输入,按升序排序,然后打印结果
- 如何在循环中使用scanf,将值存储到一个变量中,然后打印出来?
- 如何将文件逐行读取到矢量中,然后打印矢量
- 如何打印第一个和最后一个元素的和,然后打印第二个和倒数第二个元素的总和,依此类推
- C++ 如何创建 2D 数组,将其传递给另一个函数,然后打印
- 在结构向量中搜索一个数据成员,然后打印匹配的所有数据成员
- 使用队列和列表 STL 进行C++分配。在将数据填充到列表或队列中然后打印该数据时遇到问题
- 尝试将二进制数组转换为十六进制C++然后打印结果
- 如何将一个数组的每个元素与另一个元素进行比较(如果存在),然后打印是,否则否
- 带有用户输入的C 文本数组,然后打印输入
- 如何在文件中搜索关键字,然后打印其中包含的字符串
- 从文件中读取结果数据,加载它,比较它,然后打印显示
- 将结果存储在 C++Map 中,然后迭代它,然后打印出来
- 如何将结果存储在 Map 中 C++,然后迭代它,然后打印出结果
- 用"*"(特殊字符)初始化向量,然后打印出来
- 如何用自己的值填充tm结构,然后打印出来
- 按字母顺序降序对列表进行排序,然后打印列表
- 在c++中找到文本中的单词,然后打印下一个特定的行
- 如何修改以下代码,以便我实际上将文件的内容读入数组,然后打印出数组?