用"*"(特殊字符)初始化向量,然后打印出来

Initialize a vector with '*'(special character) and then print it

本文关键字:然后 打印 向量 初始化 特殊字符      更新时间:2023-10-16

我想用特殊字符初始化一个向量,然后打印出来

这是我正在使用的代码

#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

相关文章: