使用 std.algorithm 保存从数组中删除的值的更好方法
Better way to save removed value from array, using std.algorithm
我需要从数组中删除第一个元素,它存在于第二个数组中。
查看 std.algorithm 包,我可以通过 findAmong
和 remove
来完成。
但是有没有办法将它们结合起来,这样我既可以删除一个元素,又可以查看删除了哪个元素?
例如:
// array that will have elements removed
auto targetStrings = ["a", "b", "c"];
// holder for element that will be removed
string removedString;
// array to match against, to determine what should be removed
auto removeStrings = ["b", "a"];
auto r = findAmong(targetStrings, removeStrings);
if (r.count > 0) {
removedString = r[0];
targetStrings = targetStrings.remove!(c => c == removedString);
}
writeln(removedString);
writeln(targetStrings);
您可以通过从原始范围的长度中减去findAmong
返回的剩余范围的长度来获得元素的索引,然后只需将remove
与索引一起使用:
auto r = findAmong(targetStrings, removeStrings);
if (!r.empty)
{
removedString = r.front;
auto index = targetStrings.length - r.length;
targetStrings = targetStrings.remove(index);
}
或者,直接使用 countUntil
获取索引:
auto index = targetStrings.countUntil!(s => removeStrings.canFind(s));
if (index >= 0)
{
removedString = targetStrings[index];
targetStrings = targetStrings.remove(index);
}
我需要从数组中删除第一个元素,它存在于第二个数组中。
查看 std.algorithm 包,我可以通过 findAmong
和 remove
来完成。
但是有没有办法将它们结合起来,这样我既可以删除一个元素,又可以查看删除了哪个元素?
例如:
// array that will have elements removed
auto targetStrings = ["a", "b", "c"];
// holder for element that will be removed
string removedString;
// array to match against, to determine what should be removed
auto removeStrings = ["b", "a"];
auto r = findAmong(targetStrings, removeStrings);
if (r.count > 0) {
removedString = r[0];
targetStrings = targetStrings.remove!(c => c == removedString);
}
writeln(removedString);
writeln(targetStrings);
您可以通过从原始范围的长度中减去findAmong
返回的剩余范围的长度来获得元素的索引,然后只需将remove
与索引一起使用:
auto r = findAmong(targetStrings, removeStrings);
if (!r.empty)
{
removedString = r.front;
auto index = targetStrings.length - r.length;
targetStrings = targetStrings.remove(index);
}
或者,直接使用 countUntil
获取索引:
auto index = targetStrings.countUntil!(s => removeStrings.canFind(s));
if (index >= 0)
{
removedString = targetStrings[index];
targetStrings = targetStrings.remove(index);
}