简体   繁体   English

如何从结构数组中删除元素?

[英]How to remove element from array of structures?

I need to remove element from array of structures with, for example value 3 . 我需要从结构数组中删除元素,例如值为3

Here is my code: 这是我的代码:

import std.stdio;
import std.range;
import std.array;
import std.string;
import std.algorithm;
import std.conv;

void main()
{
    struct Point
    {
        int order;
        int pos;
        int val;
    }

    Point point;
    Point [] points;



    point.order = 1;
    point.pos = 1;
    point.val = 1;  
    points ~= point;

    point.order = 2;
    point.pos = 4;
    point.val = 2;  
    points ~= point;

    point.order = 3;
    point.pos = 14;
    point.val = 3;  
    points ~= point;    

    point.order = 4;
    point.pos = 24;
    point.val = 1;  
    points ~= point;        

    writeln(points);

}

I thought to do something like: 我想做类似的事情:

points.map!(a=>a.val.canFind(3).drop);

But this is do not work. 但这是行不通的。 I need to change original points array and drop element from it. 我需要更改原始points组并从中删除元素。

As I understand you want to remove the Points which have a value of 3. 据我了解,您想删除值为3的点。

The easiest is to use filter for that: 最简单的方法是使用过滤器:

points = points.filter!(a => a.val != 3).array;

Here it creates a new array but if you don't store the result you can use it lazily without any copy. 在这里它创建了一个新的数组,但是如果您不存储结果,则可以懒洋洋地使用它而无需任何副本。

If you want to reuse it though and if you do lots of such removing then I recommend that you have a look at std.algorithm:remove which removes an element given its index. 如果您想重用它,并且要进行大量此类删除操作,那么我建议您看一下std.algorithm:remove,该操作将删除给定索引的元素。 Said index can be found using std.algorithm:countUntil for example. 例如,可以使用std.algorithm:countUntil找到该索引。

Map is used to apply a transformation on each element of a set, for example [1, 2, 3].map!(x => x*2+1) == [3, 5, 7] . Map用于将变换应用于集合的每个元素,例如[1, 2, 3].map!(x => x*2+1) == [3, 5, 7] What you defined wasn't a transformation for each element so it couldn't work. 您定义的并不是每个元素的转换,因此它无法工作。 Map can't change the length of an array notably, its output is the same length as its input. Map不能显着更改数组的长度,它的输出与输入的长度相同。

EDIT: I forgot to say but this reference might be useful to you https://p0nce.github.io/d-idioms/#Adding-or-removing-an-element-from-arrays 编辑:我忘了说,但此参考资料可能对您有用https://p0nce.github.io/d-idioms/#Adding-or-removing-an-element-from-arrays

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM