在 C++11 中是否有更优雅的方法可以执行以下操作
Is there a more elegant way to do the following in C++11?
我想避免关于无符号 int 和有符号 int 之间比较的警告。
我使用如下循环:
for (int i =0 ; i < vec.size(); i++) {
// do something
}
它给出了这些警告(这本身很好,我想要高级别的警告)。
我想把它改成以下内容:
for (auto i = vec.size()*0; i < vec.size(); i++) {
// do something
}
在这种情况下,我没有得到警告。但我想知道是否有比这更优雅的东西,它会自动推断出迭代器所需的类型。
使用基于范围的 for 循环
for (auto& i : vec)
{
cout << *i;
}
使用迭代器。
for (auto it = vec.begin(), end_it = vec.end(); it != end_it; ++it)
{
cout << *it;
}
如果你想要一个计数器,如果你懒惰,请使用std::vector<T>::size_type
或size_t
。
如果这是一个选项,请首选来自 <algorithm>
的标准库高阶原语,例如(不限于):
-
std::accumulate
-
std::copy
-
std::transform
当与 lambda 一起使用时,它们非常富有表现力。仅当无法选择时才使用for
,并且更喜欢范围循环。
甚至是降序循环:
auto i = vec.size();
while (i --> 0)
// ...
因为问题以短语开头:
"我想避免关于无符号int和 签名 int"
我假设vec.size()
返回unsigned int
.
如果 vec.size()
返回的类型可以存储在unsigned int
中,则可以使用以下方法。
for (auto i = 0u; i < vec.size(); i++) {
// do something
}
否则,请使用适当的类型或检查其他答案。
如果vec
是类型 std::vector<T>
(没有提到,因此上面的代码),你也可以使用 for_each 循环(也没有提到)
std::for_each(vec.begin(), vec.end(), [](T t){ /* do something with t */ });
std::for_each(vec.begin(), vec.end(), [](T & t){ /* do something with t */});
std::for_each(vec.begin(), vec.end(), [](const T & t){ /* do something with t */ });
如果您必须使用一些已经存在的函数对象(或方法或非成员函数)遍历向量元素,它会更方便
void f(int x) { std::cout << "f: " << x << "n"; }
void g(int x) { std::cout << "g: " << x << "n"; }
...
std::vector<int> vec{1, 2, 3};
std::for_each(vec.begin(), vec.end(), std::bind(f, std::placeholders::_1)); //calls f(int)
std::for_each(vec.begin(), vec.end(), std::bind(g, std::placeholders::_1)); //calls g(int)
更方便,因为您可以保留花哨的回调并根据需要将其设置为适当的功能
std::function<void(int)> callback = std::bind(f, std::placeholders::_1);
if (userWantsG())
callback = std::bind(g, std::placeholders::_1);
std::for_each(vec.begin(), vec.end(), callback); //calls g or f
相关文章:
- 是否可以依赖函数范围的静态变量来执行程序关闭期间调用的方法?
- 找到一种有效的方法,在 2 个巨大的缓冲区上执行 MAX,每字节字节
- 如何将成员函数作为参数传递并在派生对象上执行方法列表
- 如何使父类不重复已经执行的祖父方法
- 如何将带有参数的方法传递给线程以执行?
- 在C++中执行 N 阶乘编译时间的 3 种不同/相同方法
- 在 c++ 中从执行的 shell 命令获取返回状态的安全方法是什么?
- 在高通六边形处理器的word32上执行水平求和的最快方法是什么
- 在C++中执行方法的同一行中传递指针
- 在 MySQL 连接器C++ API 中使用一个函数调用执行多个查询的正确方法是什么?
- 如何执行重写的方法C++
- 基于整数向量执行位排列的有效方法?
- 执行模板参数包指向的所有方法
- cppUnit:针对多个测试方法执行一次的设置函数
- 检查子类是否执行了方法重写
- 通过调试来检查C 中单行表达式执行顺序的方法
- 如何在不冻结线程/应用程序的情况下减慢方法执行速度
- 如何在 COM 中对方法执行返回类型
- 在对类方法执行指针部分专用化时获取"illegal use of explicit template arguments"
- 继承,选择性方法执行