我有这个c ++代码可以正常删除列表的最后3个元素,但我想知道这是否是正确的方法来做这样的事情,因为我担心删除迭代器问题的元素.代码基本上采用6个元素"Groups"的列表,将其分为2个较小的列表"Group1"和"Group2",然后将不同的List"GroupToCompare"与"Group2"进行比较,如果它们相等,则删除最后一个"团体"的3个要素.
#include "pch.h"
#include <iostream>
#include <iostream>
#include <string>
#include <list>
using namespace std;
int main()
{
std::list <string> Groups = {};
Groups = { "Spike", "Jet", "Faye", "Edward", "Vincent", "Elektra" };
std::list<string> Group1 = {};
std::list<string> Group2 = {};
std::list<string> GroupToCompare = {};
GroupToCompare = { "Edward", "Vincent", "Elektra" };
size_t half1 = Groups.size() / 2;
std::list<std::string>::iterator ig = Groups.begin();
advance(ig, half1);
Group1.insert(Group1.end(), Groups.begin(), ig);
Group2.insert(Group2.end(), ig, Groups.end());
std::list<std::string>::iterator removeIt = Groups.begin();
advance(removeIt, half1);
cout << "List Elements 1: " << endl;
std::list<string>::iterator itrofList = Group1.begin();
string firstvar;
for (itrofList = Group1.begin(); itrofList != Group1.end(); ++itrofList) {
firstvar = *itrofList;
cout << "Item: " << firstvar << endl;
}
cout << "List Elements 2: " << endl;
std::list<string>::iterator itrofList1 = Group2.begin();
string firstvar1;
for (itrofList1 = Group2.begin(); itrofList1 != Group2.end(); ++itrofList1) {
firstvar1 = *itrofList1;
cout << "Item: " << firstvar1 << endl;
}
if (Group2 == GroupToCompare) {
removeIt = Groups.erase(removeIt);
removeIt = Groups.erase(removeIt);
removeIt = Groups.erase(removeIt);
}
cout << "List Elements of Groups after removing the last 3 elements: " << endl;
std::list<string>::iterator itrofList2 = Groups.begin();
string firstvar2;
for (itrofList2 = Groups.begin(); itrofList2 != Groups.end(); ++itrofList2) {
firstvar2 = *itrofList2;
cout << "Item: " << firstvar2 << endl;
}
}
Run Code Online (Sandbox Code Playgroud)
有没有更正确的方法,以防我想删除列表末尾的更多元素,并避免删除迭代器的问题?提前致谢!
即使std::list::erase()多次使用返回的位置调用,调用正确的重载也有助于提高可读性和性能:
iterator erase( iterator first, iterator last );
Run Code Online (Sandbox Code Playgroud)
例:
std::list<int> l{1, 2, 3, 4, 5};
l.erase(std::prev(l.end(), 3), l.end());
// l is {1, 2}
Run Code Online (Sandbox Code Playgroud)
注意:原样,如果l大小不是3 ,则此代码会显示未定义的行为.
| 归档时间: |
|
| 查看次数: |
135 次 |
| 最近记录: |