我搜索了一下,我很惊讶这还没有被问到。我知道如何用一个简单的循环来做到这一点,那么使用矢量迭代器呢?
for( std::vector<int>::iterator it = somevector.begin(); it != somevector.end(); ++it )
{
//Conditions stating a certain vector has an even or odd index.
}
抱歉没有澄清,我的意思是检测向量的索引是奇数还是偶数。
这将是一种简单的方法:
{
bool is_even = true;
for (const auto& v: somevector) {
if (is_even) even_handler(v);
else odd_handler(v);
is_even = !is_even;
}
}
想要更复杂的解决方案?没问题:
#include <iostream>
#include <string>
#include <utility>
#include <vector>
using std::next;
template<typename Iter, typename Func, typename...Funcs>
void RotateHandlers(Iter b, Iter e, Func f, Funcs...fs) {
if (b != e) {
f(*b);
RotateHandlers(next(b), e, fs..., f);
}
}
int main() {
std::vector<std::string> v({"Hello", "world", "it's", "really", "great", "to", "be", "here"});
RotateHandlers(v.begin(), v.end(),
[](const std::string& s){std::cout << "First|" << s << std::endl;},
[](const std::string& s){std::cout << "Then |" << s << std::endl;},
[](const std::string& s){std::cout << "And |" << s << std::endl
<< " |" << std::string(s.size(), '-') << std::endl;}
);
return 0;
}
在这里看到它:http: //ideone.com/jmlV5F
我猜你的意思是你想检测当前索引是偶数还是奇数:
#include <iostream>
#include <iterator>
#include <vector>
int main()
{
std::vector<int> somevector;
somevector.push_back(1);
somevector.push_back(2);
somevector.push_back(4);
somevector.push_back(8);
somevector.push_back(111605);
for (auto it = somevector.begin(); it != somevector.end(); ++it)
{
// current index
const auto index = std::distance(somevector.begin(), it);
if ((index % 2) == 0) // even
{
std::cout << "Index " << index << " (even) is: " << *it;
}
else
{
std::cout << "Index " << index << " (odd) is: " << *it;
}
std::cout << std::endl;
}
}
您可以使用 获取迭代器之间的距离std::distance
。(索引是距起点的距离。)
如果我[在最后一次编辑之前]正确理解了这个问题,一个选项是:
bool is_odd(const std::vector<int> &somevector) {
for( std::vector<int>::iterator it = somevector.begin(); it != somevector.end(); ++it ) {
//Conditions stating a certain vector is even or odd.
if (*it % 2 == 0) {
return false;
}
}
return true;
}
分别用于“偶数向量”。