std::deque<int> data {10, -5, 12, -6, 10, 8, -7, 10, 11}; std::replace(std::begin(data), std::end(data), 10, 99); // Result: 99 -5 12 -6 99 8 -7 99 11这里,data 容器中和 10 匹配的全部元素都会被 99 替代。
string password { "This is a good choice !"}; std::replace_if(std::begin(password), std::end(password),[](char ch){return std::isspace(ch);}, '_'); //Result:This_is_a_good_choice!这个谓词会为任何是空格字符的元素返回 true,因此这里的空格都会被下划线代替。
std::vector<string> words { "one","none", "two", "three", "none", "four"}; std::vector<string> new_words; std::replace_copy (std::begin (words), std::end(words), std::back_inserter (new_words), string{"none"}, string{"0"}); // Result:"one", "0", "two","three","0","four"在执行这段代码后,new_words 会包含注释中的 string 元素。
std::deque<int> data {10, -5, 12, -6, 10, 8, -7, 10,11}; std::vector<int> data_copy; std::replace_copy_if(std::begin(data), std::end(data),std::back_inserter(data_copy),[](int value) {return value == 10;}, 99); // Result:99 -5 12 -6 99 8 -7 99 11data_copy 是一个 vector 容器,这里使用它只是为了说明输出容器可以和输入容器不同。这段代码执行后,它会包含注释中所示的元素。
Copyright © 广州京杭网络科技有限公司 2005-2025 版权所有 粤ICP备16019765号
广州京杭网络科技有限公司 版权所有