使用正向迭代器进行反向迭代
Reverse iterate using forward iterator
我有一个功能,我想比较集合中的每个元素与前面的元素。我想这样做:
std::set<int> sSet;
std::set<int>::iterator it;
std::set<int>::iterator itR;
sSet.insert(1);
sSet.insert(2);
sSet.insert(3);
sSet.insert(4);
sSet.insert(5);
sSet.insert(6);
for (it=sSet.begin(); it!=sSet.end(); ++it) //simple forward loop
{
itR = it;
if(it != sSet.begin())
itR--;
for(;itR!=sSet.begin();itR--)
{
//Reverse iteration
//for comparing every element to all the previous elements
//Problem here is it goes up to the second element only and not first
//because of the condition itR!=sSet.begin()
}
}
我想在这里使用反向迭代器,但是我又找不到从特定位置(或正向迭代器)设置反向迭代器的方法。
有正确的方法来做这件事吗?
Update:上面使用的设置只是为了演示。实际实现为类的集合,定义如下:
std::set<TBigClass, TBigClassComparer> sSet;
class TBigClassComparer
{
public:
bool operator()(const TBigClass s1, const TBigClass s2) const
{
//comparison logic goes here
}
};
要反转吗?!使用反向迭代器:
std::set<int> sSet;
std::set<int>::iterator it;
std::reverse_iterator<std::set<int>::iterator> itR;
sSet.insert(1);
sSet.insert(2);
sSet.insert(3);
sSet.insert(4);
sSet.insert(5);
sSet.insert(6);
for (it=sSet.begin(); it!=sSet.rend(); ++it) //simple forward loop
{
itR = std::reverse_iterator<std::set<int>::iterator>(it);
for(;itR!=sSet.rbegin();++itR)
{
//Reverse iteration
//for comparing every element to all the previous elements
//Problem here is it goes up to the second element only and not first
//because of the condition itR!=sSet.begin()
}
}
但是,请注意,当迭代器反转时,反转的版本并不指向范围内的相同元素,而是指向它前面的元素。这样做是为了安排范围的过尾元素:指向范围中过尾元素的迭代器,在反转时,将被更改为指向范围的最后一个元素(而不是超过它)(如果反转,这将是范围的第一个元素)。如果指向范围内第一个元素的迭代器被反转,则反转后的迭代器指向第一个元素之前的元素(如果反转,这将是范围的后端元素)。
可以使用内部while循环:
while (true)
{
// do your comparison here
if (itR == sSet.begin())
break;
--itR;
}
相关文章:
- 使用std::multimap迭代器创建std::list
- 来自 std::list 的迭代器 .end() 按预期返回"0xcdcdcdcdcdcdcdcd"但 .begin()
- C++中带有List类的迭代器Segfault
- 如何在c++迭代器类型中包装std::chrono
- 集合上的输出迭代器:assign和increment迭代器
- Boost Spirit,获取迭代器内部语义动作
- 对于set上的循环-获取next元素迭代器
- 为什么output_editor Concept不需要output_e迭代器标记
- c++17文件系统::recursive_directory迭代器()在mac上没有给出这样的目录,但在windows上
- 使用迭代器时如何访问对象在向量中的位置?
- std::vector::迭代器是否可以合法地作为指针
- 跟随整数索引列表的自定义类迭代器
- 不明白迭代器,引用和指针失效,一个例子
- 我可以使用反向迭代器作为ForwardIt吗
- ESP8266单片机矢量迭代器的C++问题
- 如何在C++中将迭代器作为函数参数传递
- 是否应避免从非常量迭代器转换为常量迭代器?
- 如何在 c++ 中将字符串迭代器变量传递给函数?
- 为什么 vector 的随机访问迭代器给出与指针不同的内存地址?
- 为什么 C++ std::unordered_map 从 emplace/ 找到返回一个迭代器?