通过包裹环绕的C 向量迭代
Iterating through a C++ vector with wrap-around
我有一个通过向量迭代的分配,并删除每个第三个数字。如果它撞到向量的末端,则应从第一个条目开始继续计数,直到仅保留一个数字为止。用户输入向量中应有多少个数字。
我很难习惯向量和数组之间的区别 - 就在上周,我们遇到了一个问题,涉及在数组中包裹的问题,该数组已通过mod解决,但我很快发现这对向量不起作用。
到目前
while (vector.size > 1) {
for(std::vector<int>::iterator i = suitors.begin(); i <= suitors.end(); i++) {
// here, add a case for if it hits the end, start over
if (i = suitors.end()) {
i = suitors.begin();
}
suitors.erase(suitors.at(i) + 2);
}
我遇到的问题是弄清楚如何重新开始,因为当我尝试以这种方式使用i时出现错误。
有什么建议或提示让我走上正确的道路?我开始看到多功能矢量的多样性,但是它们还没有点击。我也不确定是否有更好的方法可以阻止它以外的循环。
我会使用remove_if
将矢量中的项目移动到每次索引变量时,每次达到3。
#include <iostream>
#include <vector>
#include <algorithm>
int main()
{
std::vector<int> v{1,2,3,4,5,6};
unsigned index = 0; // this is the index variable used to remove elements
auto end = v.end(); // point to the current end of the vector
// keep looping until there is only 1 element in the vector
while(std::distance(v.begin(), end) > 1) {
// remove_if will call the predicate for each element
// the predicate simply increments the index each time, and when it reaches
// 3 indicates that element should be removed
// remove_if will move items to the end of the vector and return an
// iterator to the end of the new range, so we'll update the end variable
// with the result
end = std::remove_if(v.begin(), end, [&index](int) {
if(++index == 3) {
// reset the index and indicate this element should be removed
return (index = 0), true;
}
return false;
});
for(auto iter = v.begin(); iter != end; ++iter) {
std::cout << *iter << ' ';
}
std::cout << 'n';
}
// erase all the elements we've removed so far
v.erase(end, v.end());
}
输出:
1 2 4 5
1 2 5
1 5
1
实时演示
我假设只要向量具有多个元素,我假设的循环意味着要走,但这应该包含在for中,而不是另一个循环
句法问题在IF中:
if (i = suitors.end())
// ^ should be ==
否则,您只是将终点分配给迭代器
for(std::vector<int>::iterator i = suitors.begin(); suitors.size() > 1; ++i) {
// ^ loop condition changed
if (i == suitors.end()) {
i = suitors.begin();
}
suitors.erase(suitors.at(i) + 2);
}
在您迭代其迭代时修改容器很危险。
相关文章:
- std::向量迭代器和调整大小/保留的奇怪/有趣行为
- 如何取消引用向量迭代器
- Map中的(字符串的)向量迭代器
- C++将向量迭代器转换为索引
- yaml-cpp到std::向量迭代的怪异行为
- 使用索引与迭代器将向量迭代到倒数第二个元素
- 无法取消引用超出范围的向量迭代器 - 有什么问题?
- 向量迭代器不兼容的错误,用于保存另一个向量的迭代器的向量
- C++向量迭代器nth_element编译错误
- 无法查找值初始化的向量迭代器?
- C++向量迭代:常量 vs. 常量自动 vs. 无常量
- 向量迭代编译为非常不同的指令
- STD ::向量迭代器类型和允许的操作
- 如何通过尺寸未知的2D向量迭代
- 向量迭代器 < 或 !=
- 如何通过共享_ptr向量迭代
- 如何通过向量迭代作为指针
- 通过向量迭代,而其他线程可能会对其进行修改
- 我如何通过C 中的字符串向量迭代
- 向量迭代器在新对象的 push_back() 之后不兼容