我使用std::erase_if捕获的计数器从容器中删除一半元素,如下所示。C++20 编译为gcc10
#include <iostream>
#include <vector>
#include <map>
#include <unordered_map>
int main()
{
{
std::vector<int> container(10);
std::cout << container.size() << std::endl;
std::erase_if(container, [i = 0u](auto&&...) mutable { return i++ % 2 == 0; });
std::cout << container.size() << std::endl;
}
std::cout << std::endl;
{
std::map<int, int> container;
for (int i = 0; i < 10; i++) {
container.emplace(i, i);
}
std::cout << container.size() << std::endl;
std::erase_if(container, [i = 0u](auto&&...) mutable { return i++ % 2 == 0; …Run Code Online (Sandbox Code Playgroud) 我知道std::optional<T&>标准不支持这一点。这个问题是关于是否通过std::optional<T>&有性能优势
示例代码(https://godbolt.org/z/h56Pj6d6z)复制在这里
#include <ctime>
#include <iomanip>
#include <iostream>
#include <optional>
void DoStuff(std::optional<std::string> str) {
if (str) std::cout << "cop: " << *str << std::endl;
}
void DoStuffRef(const std::optional<std::string>& str) {
if (str) std::cout << "ref: " << *str << std::endl;
}
int main() {
std::optional<std::string> str = {};
DoStuff(str);
DoStuffRef(str);
str = "0123456789012345678901234567890123456789";
DoStuff(str);
DoStuffRef(str);
}
Run Code Online (Sandbox Code Playgroud)
(我的实际用例对于复杂的用户定义类型是可选的,但我希望长字符串在编译器方面也能做同样的事情)
在这种情况下,DoStuffRef与 相比,实际上是否节省了任何复制工作DoStuff?
我试图查看 godbolt 输出,但我不知道足够的汇编来确定。我确实看到,在 的情况下DoStuff,似乎std::optional<T>创建了一个不存在的临时文件DoStuffRef,所以我怀疑是的,optional …
我有办法
void func(int bar, std::string_view sv = {})
Run Code Online (Sandbox Code Playgroud)
但是现在我想使用以下方法设置sv的默认值
const char def = 'X'
Run Code Online (Sandbox Code Playgroud)
我该如何实现?谢谢!