从 Vector 中删除一个元素并将其余元素向下移动 - C++
Delete an element from a Vector and move rest of elements down - C++
我有一个矢量 'simpleVector' :
struct SimpleStruct
{
XMFLOAT3 hello;
XMFLOAT3 hi;
};
std::vector <SimpleStruct> simpleVector(0);
我正在尝试删除一个元素,例如 simpleVector[3],然后将其余元素向下移动一个以删除空白 space。
simpleVector.erase(std::remove_if(simpleVector.begin(), simpleVector.end(),
[](int i) { return i == 3; }), simpleVector.end());
However, I get this error: cannot convert argument 1 from
'SimpleStruct' to 'int'.
如果这很明显,请原谅我,我是 C++ 的新手。我怎样才能消除这个问题?
传递给 std::remove_if
的一元谓词需要能够接受 SimpleStruct
。它的目的是评估向量的每个元素是否应该是 "removed"。
您的谓词接受 int
,并且没有从 SimpleStruct
到 int
的转换。您需要将谓词更改为有意义的内容。
另一方面,如果您想删除 simpleVector[3]
处的元素,您只需要
simpleVector.erase(simpleVector.begin() + 3);
如果你想删除索引 3 处的元素,你可以这样做:
simpleVector.erase(simpleVector.begin()+3);
使用 std::vector
,您无需明确 'move all the other elements down' - 它会在 erase
.
之后为您执行此操作
要删除索引 3 处的元素,请改为执行以下操作:
simpleVector.erase( simpleVector.begin() + 3 );
另请注意,您不必担心将其余元素向下移动,因为向量会自动为您处理。
Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).
– cplusplus.com
我有一个矢量 'simpleVector' :
struct SimpleStruct
{
XMFLOAT3 hello;
XMFLOAT3 hi;
};
std::vector <SimpleStruct> simpleVector(0);
我正在尝试删除一个元素,例如 simpleVector[3],然后将其余元素向下移动一个以删除空白 space。
simpleVector.erase(std::remove_if(simpleVector.begin(), simpleVector.end(),
[](int i) { return i == 3; }), simpleVector.end());
However, I get this error: cannot convert argument 1 from 'SimpleStruct' to 'int'.
如果这很明显,请原谅我,我是 C++ 的新手。我怎样才能消除这个问题?
传递给 std::remove_if
的一元谓词需要能够接受 SimpleStruct
。它的目的是评估向量的每个元素是否应该是 "removed"。
您的谓词接受 int
,并且没有从 SimpleStruct
到 int
的转换。您需要将谓词更改为有意义的内容。
另一方面,如果您想删除 simpleVector[3]
处的元素,您只需要
simpleVector.erase(simpleVector.begin() + 3);
如果你想删除索引 3 处的元素,你可以这样做:
simpleVector.erase(simpleVector.begin()+3);
使用 std::vector
,您无需明确 'move all the other elements down' - 它会在 erase
.
要删除索引 3 处的元素,请改为执行以下操作:
simpleVector.erase( simpleVector.begin() + 3 );
另请注意,您不必担心将其余元素向下移动,因为向量会自动为您处理。
Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list). – cplusplus.com