gpt4 book ai didi

C++ "vector iterator not decrementable"?

转载 作者:行者123 更新时间:2023-11-28 03:41:23 25 4
gpt4 key购买 nike

我正在尝试解决 this UVa problem .

我正在尝试使用 Vector 来解决问题。我需要模拟循环链表之类的东西,所以我使用迭代器来访问元素。但是在尝试之后,我发现 Vector 迭代器在递增和递减方面有一些问题,并且我无法通过使用 reverse_iterator 作为参数来删除元素。我现在很困惑。我的代码有什么问题是因为我错过了一些重要的细节还是我应该用其他方式解决这个问题??

提前致谢。

这是我的代码

#include <iostream>
#include <vector>
#include <iomanip>

using namespace std;

vector<int> people;

int main()
{
int n, k, m; // k -> counter clockwise, m -> cloclwise
while (cin >> n >> k >> m)
{
if (n == 0 && k == 0 && m == 0)
return 0;
for (int i = 1; i <= n; i++)
people.push_back(i);
vector<int>::iterator k_pos = people.begin();
vector<int>::reverse_iterator m_pos = people.rbegin();

//cout << n << " " << k << " " << m << endl;

while (!people.empty())
{
int k_choose, m_choose;
for (int i = 1; i < k; i++)
{
k_pos++;
if (k_pos == people.end()) // if reach the end, go to begin
k_pos = people.begin();
}

k_choose = *k_pos;
cout << k_choose << endl;

for (int i = 1; i < m; i++)
{
m_pos++;
if (m_pos == people.rend())
m_pos = people.rbegin();
}

m_choose = *m_pos;


if (k_choose == m_choose)
{
cout << setw(3) << k_choose << ",";
people.erase(k_pos); // erase the element
}

else
{
cout << setw(3) << k_choose << setw(3) << m_choose << ",";
k_pos = people.erase(k_pos); // erase the element
//vector<int>::iterator temp;
//for (temp = people.begin(); *temp != *m_pos; temp++)
//{
//}
//cout << "ok" << endl;
people.erase(--m_pos.base());*****problem

}
vector<int>::iterator temp;
for (temp = people.begin(); temp != people.end(); temp++)
cout << *temp << endl;

k_pos++; *****problem
if (k_pos == people.end()) // point to next
k_pos = people.begin();

m_pos++; *****problem
if (m_pos == people.rend()) // point to next
m_pos = people.rbegin();
}
}
return 0;
}

最佳答案

在删除或插入 vector 后,指向它的所有迭代器可能会变得无效(如果 vector 被重新分配)。这就是为什么在 else 中执行删除后 m_pos 可能会变得无效。我的建议是使用索引(至少我在竞争性编程中是这样做的)。

关于C++ "vector iterator not decrementable"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9118137/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com