# C++初学者指南-5.标准库(第二部分)--更改元素算法

57 篇文章 1 订阅
52 篇文章 2 订阅

## C++初学者指南-5.标准库(第二部分)–更改元素算法

### 填充/覆盖范围

#### fill / fill_n

std::vector<int> v {1,0,9,0,9,1,0,1};
fill(begin(v)+2, begin(v)+7, 2);
for (int x : v) { cout << x << ' '; }  // 1 0 2 2 2 2 2 1

std::vector<int> v {1,0,9,0,9,1,0,1};
fill_n(begin(v)+2, 5, 2);
for (int x : v) { cout << x << ' '; }  // 1 0 2 2 2 2 2 1


#### generate / generate_n

auto gen = [i=0]() mutable { i += 2; return i; };
//     init-^^^    ^^^^^^^⇒ member 'i' changeable!
cout << gen();  // 2
cout << gen();  // 4
cout << gen();  // 6


class int_range_generator {
int val_  = 0;
int step_ = 1;
public:
int_range_generator () = default;
explicit constexpr
int_range_generator (int start, int step=1) noexcept:
val_{start}, step_{step} {}
constexpr int operator () () noexcept {
int const old = val_;
val_ += step_;
return old;
}
};
auto gen = int_range_generator{2,2};
cout << gen();  // 2
cout << gen();  // 4
cout << gen();  // 6

auto gen = [i=0]() mutable { i += 2; return i; };
std::vector<int> v;
v.resize(7,0);
generate(begin(v)+1, begin(v)+5, gen);
for (int x : v) { cout << x << ' '; }  // 0 2 4 6 8 0 0

auto gen = [i=0]() mutable { i += 2; return i; };
std::vector<int> v;
v.resize(7,0);
generate_n(begin(v)+1, 4, gen);
for (int x : v) { cout << x << ' '; }  // 0 2 4 6 8 0 0


### 更改/替换值

#### transform

// f: 'x' → "<x>"
auto f = [](char c) { return std::string("<") + c + ">"; };
std::string in = "vwxyza";
std::vector<std::string> out;
// make sure 'out' can fit result
out.resize(4);
transform(begin(in)+1, begin(in)+5, begin(out), f);
for (auto const& x : out) { cout << x << ' '; }  // <w> <x> <y> <z>


// f: 'y',3 → "yyy"
auto f = [](char c, int i) { return std::string(i,c); };
std::string in1 = "wxy";
std::vector<int> in2 = {1,2,3};
std::vector<std::string> out;
// make sure 'out' can fit result
out.resize(3);
transform(begin(in1), end(in1), begin(in2), begin(out), f);
for (auto const& x : out) { cout << x << ' '; }  // w xx yyy


#### replace / replace_if

std::vector<int> v {1,2,3,2,4,2,2,6};
replace(begin(v)+2, begin(v)+7, 2, 0);
for (int x : v) { cout << x << ' '; }  // 1 2 3 0 4 0 0 6


#### replace_copy / replace_copy_if

std::vector<int> in {1,2,3,2,4,2,2,6,7};
std::vector<int> out;
out.resize(5);
replace_copy(begin(in)+2, begin(in)+7, begin(out), 2, 0);
for (int x : out) { cout << x << ' '; }  // 3 0 4 0 0

auto const is_even = [](int x) { return !(x & 1); };
std::vector<int> in {2,3,2,5,4,6,6};
std::vector<int> out;
out.resize(5);
replace_copy_if (begin(in)+1, begin(in)+7, begin(out), is_even, 0);
for (int x : out) { cout << x << ' '; }  // 3 0 5 0 0


### 相关内容

• 12
点赞
• 15
收藏
觉得还不错? 一键收藏
• 0
评论

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、付费专栏及课程。