我想检查一个 vector ,如果它的元素同时具有整数 A 和 B,删除它们之间的元素并复制到另一个 vector 。例如,有两个 vector ; vector<> path
和 vector<> v1
Path v1
---A***B## ---AB##
所以任务是删除A和B之间的元素 这是一个 C++ 代码,但不幸的是它不起作用。有什么问题吗?
vector< > Path,v1;
vector<int>::iterator it2,it3;
int A,B;
it2=find(Path.begin(), Path.end(), A) ;
it3=find(Path.begin(), Path.end(), B) ;
vector<int> v1(Path.begin(),Path.end());
if (it2 != Path.end() && it3 != Path.end())
{
if(it2<it3)
{
v1.erase(it2+1,it3);
}
else
{
v1.erase(it3+1,it2);
}
}
最佳答案
首先,您要在 if block 中创建一个新的 v1
,但我很确定您想要分配给已经存在的那个。您还将 Path
vector 中的迭代器传递给 v1
的删除函数,从而导致未定义的行为。我还会通过首先不添加不需要的元素来保存 v1.erase
完成的工作。
if (it2 != Path.end() && it3 != Path.end())
{
if(it3<it2)
{
std::swap(it2,it3);
}
++it2; // simplifies logic later
// optional step to possibly save an allocation
size_t total = std::distance(Path.begin(), it2);
total += std::distance(it3,Path.end());
v1.reserve(total);
v1.assign(Path.begin(), it2);
v1.insert(v1.end(), it3, Path.end());
}
请注意,如果 A==B
,则会将该元素添加两次。我不确定这是否是所需的行为,但它符合您的问题描述。
关于c++ - 如何删除 vector 中的元素(或 A 和 B 之间的距离),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19480611/