Swift:按键引用数组元素(Swift: reference to array element by key)

我编写了自己的小函数来使用键在数组中查找元素。 但我确信在Swift中有一个可以使用的实现来将它放在一行中。 任何提示?

func objectAtKey(array: [T], key: String) -> T? {
    for element in array {
        if element.name == key {
            return element
        }
    }
    return nil
}

我也知道函数indexOf,但这返回一个索引,我必须用于进一步的访问。 我认为这比较慢:

let index = array.indexOf({$0.name == key})

I have written my own small function to find an element in an array using a key. But I'm sure there is a ready to use implementation in Swift to get it in one line. Any hint?

func objectAtKey(array: [T], key: String) -> T? {
    for element in array {
        if element.name == key {
            return element
        }
    }
    return nil
}

I also know function indexOf, but this return an index, I have to use for further access. I think this is slower:

let index = array.indexOf({$0.name == key})

原文:https://stackoverflow.com/questions/39236301
2022-09-06 09:09

满意答案

优雅的解决方案是提供与比较器运算符的intersect (例如,在C ++中 )。
不幸的是,Matlab似乎并不支持这种功能/灵活性。

解决您的问题的方法是

% convert structs into matrices
A = [[a(:).x];[a(:).y]]';
B = [[b(:).x];[b(:).y]]';
% intersect the equivalent representation
[C, ia, ib] = intersect( A, B, 'rows' );
% map back to original structs
c = a(ia);

或者,您是否考虑使用从句柄类派生的类对象替换结构? 有可能重载类的关系运算符 ,然后应该可以直接对类对象进行排序(我没有仔细研究过这个解决方案 - 这只是我头脑中的一个提议)。


The elegant solution would have been to supply intersect with a comparator operator (like in , e.g., C++).
Unfortunaetly, Matlab does not seem to support this kind of functionality/flexibility.

A workaround for your problem would be

% convert structs into matrices
A = [[a(:).x];[a(:).y]]';
B = [[b(:).x];[b(:).y]]';
% intersect the equivalent representation
[C, ia, ib] = intersect( A, B, 'rows' );
% map back to original structs
c = a(ia);

Alternatively, have you considered replacing your structs with class objects derived from handle class? It might be possible to overload the relational operators of the class and then it should be possible to sort the class objects directly (I haven't looked closely into this solution - it's just a proposal off the tip of my head).

相关问答

更多

如何在MATLAB中初始化一个结构体数组?(How to initialize an array of structs in MATLAB?)

使用repmat是预分配结构体的最有效方法: N = 10000; b = repmat(struct('x',1), N, 1 ); 这比使用Matlab 2011a要快10倍,而不是通过索引进行预分配 N = 10000; b(N).x = 1 索引方法只是稍微快于未预分配。 No preallocation: 0.075524 Preallocate Using indexing: 0.063774 Preallocate with re...

在Matlab中找到两个数组结构的交集(find the intersection of two array structs in Matlab)

优雅的解决方案是提供与比较器运算符的intersect (例如,在C ++中 )。 不幸的是,Matlab似乎并不支持这种功能/灵活性。 解决您的问题的方法是 % convert structs into matrices A = [[a(:).x];[a(:).y]]'; B = [[b(:).x];[b(:).y]]'; % intersect the equivalent representation [C, ia, ib] = intersect( A, B, 'rows' ); % ma...

在matlab中找到两条线的交点(Find the intersection point of two lines in matlab)

正如评论者提到的那样,并不能保证能够找到解决方案。 但是,您可以系统地确定解决方案是否存在,以及解决方案是否存在。 我将在大多数伪代码中描绘该方法: 用点和方向的归一化单位向量表示每条线是最容易的。 给定A线上的A1,A2和B线上的B1,B2,可以按如下方式进行: pA = A1, uA = (A2-A1)/norm(A2-A1). pB = B1, uB = (B2-B1)/norm(B2-B1). 注意, norm(uA) = 1 , norm(uB) = 1 。 然后沿着A线的点可以表示为...

如何在Matlab中找到两个分布的交集(How to find intersection of two distribution in Matlab)

我会修改你的方法如下: 使用pdf 比率 ,而不是差异。 这样你就可以避免在交叉点之外检测到尾部。 最小化 ,而不是应用阈值。 Vectorize :一次计算所有点的比率(然后最小化)。 换一种说法: [~, index] = min(abs(Ray./Ric-1)); 在你的例子中,这给出了 >> index index = 2107 作为x索引的函数的pdf如下。 找到的intesection索引被认为是正确的(图中略高于2000): I would modify your app...

在MATLAB中找到两个结构数组的交集(Find the intersection of two arrays of structs in MATLAB)

什么错误信息相交给你? 这应该会给你一个提示,说明为什么它不起作用。 要完成你想要的任务,你不需要你的findPost函数(它有一个在postsFound=0;什么都不做的赋值postsFound=0;以及一个误导性命名的变量matchFound ,顺便说一句。),你可以使用逻辑索引。 iRed = strcmpi({InfoArray.FavouriteColor},'red'); iLondon = strcmpi({InfoArray.City},'London'); InfoArray(i...

两个数组之间的交集[重复](Intersection between two arrays [duplicate])

我认为以下代码可以帮助您 /* package whatever; // don't place package name! */ import java.util.*; import java.lang.*; import java.io.*; /* Name of the class has to be "Main" only if the class is public. */ class Ideone { public static void main (String[] args) ...

使用结构组合Matlab文件(Combining Matlab files using structs)

根据Wolfie和烧杯的评论,下面是两个解决方案:一个使用最初提出的单元阵列样式,另一个使用数值数组而不是单元阵列(如果您只希望数字数据如你的例子)。 使用单元格数组: function [] = myFunction() % create a struct with the different vars W = struct('Band7', {7, 1099, 236, 260, 236, 260, 0},... 'Band2', {2, 1078, 236, 300...

在Matlab中找到两个正态分布的交集(Find intersection of two normal distributions in Matlab)

我知道你想要的是交叉点,而不是两条曲线下面的区域。 如果这是准确的,那么使用匿名函数会更容易, mu1 = 0; mu2 = 1; sigma1 = sqrt(0.5); sigma2 = sqrt(0.5); dist1 =@(x) exp(-(x-mu1).^2 / (2*sigma1^2)) / sqrt(2*sigma1^2*pi); dist2 =@(x) exp(-(x-mu2).^2 / (2*sigma2^2)) / sqrt(2*sigma2^2*pi); fzero(@(x) ...

在MATLAB中没有for循环的多个数组的交集(Intersection of multiple arrays without for loop in MATLAB)

这是一个使用unique和accumarray的矢量化方法,假设在输入单元阵列的每个单元格中没有重复 - [~,~,idx] = unique([tsCell_time{:}],'stable') out = tsCell_time{1}(accumarray(idx,1) == length(tsCell_time)) 样品运行 - >> tsCell_time = {[1 6 4 5],[4 7 1],[1 4 3],[4 3 1 7]}; >> InterSection = tsCell...

搜索结构的matlab单元格数组中的索引(Search indices in matlab cell array of structs)

矢量化是避免循环和编写快速代码的主要工具。 将相同的操作应用于同类的许多元素时,可以使用它。 在这种情况下,您需要相同的操作,但元素是不同的。 使用循环(cellfun是)是唯一的可能性。 >> find(cellfun(@(x)(x.id),arr)==37) ans = 5 6 7 8 9 10 使用您描述的应用程序,我希望您将重复使用此行,至少要使用我建议使用函数的干净代码 >> cellfield=@(data,field)(cellf...

相关文章

更多

The content of element type "package" must match "...

在编写后台登陆模块时,将许多默认的设置放在一个名为default的package 里。然后再定义其他 ...

如何取得Map当中的key

我定义了一个Map:Map<BufferedImage,Rectangle[]> map ...

Java 数组

Java 数组 数组对于每一门编辑应语言来说都是重要的数据结构之一,当然不同语言对数组的实现及处 ...

报错说找不到abbrev这个方法,但Array有这个方法的吧?

以下是ruby-doc.org http://www.ruby-doc.org/core/class ...

别拿Hadoop map key当id使

在写mapreduce时,发现一个问题: Hadoop的map函数的key一般是输入文件的行号,于是乎 ...

jqgrid 中组合框的值和key

在jqgrid中有一个组合框 {name:"sts",index:"s ...

自定义实现Hadoop Key-Value

自定义实现Value: 如果需要自定义一个一个Value类型,那么需要实现Hadoop预定义接口org ...

最新问答

更多

获取MVC 4使用的DisplayMode后缀(Get the DisplayMode Suffix being used by MVC 4)

我用Google搜索了一个解决方案。 “EnumDisplayModeProvider”是我自己设置网站的各种模式的枚举。 public EnumDisplayModeProvider GetDisplayModeId() { foreach (var mode in DisplayModeProvider.Instance.Modes) if (mode.CanHandleContext(HttpContext)) {

如何通过引用返回对象?(How is returning an object by reference possible?)

这相对简单:在类的构造函数中,您可以分配内存,例如使用new 。 如果你制作一个对象的副本,你不是每次都分配新的内存,而是只复制指向原始内存块的指针,同时递增一个也存储在内存中的引用计数器,使得每个副本都是对象可以访问它。 如果引用计数降至零,则销毁对象将减少引用计数并仅释放分配的内存。 您只需要一个自定义复制构造函数和赋值运算符。 这基本上是共享指针的工作方式。 This is relatively easy: In the class' constructor, you allocate m

矩阵如何存储在内存中?(How are matrices stored in memory?)

正如它在“熵编码”中所说的那样,使用Z字形图案,与RLE一起使用,在许多情况下,RLE已经减小了尺寸。 但是,据我所知,DCT本身并没有给出稀疏矩阵。 但它通常会增强矩阵的熵。 这是compressen变得有损的点:输入矩阵用DCT传输,然后量化量化然后使用霍夫曼编码。 As it says in "Entropy coding" a zig-zag pattern is used, together with RLE which will already reduce size for man

每个请求的Java新会话?(Java New Session For Each Request?)

你是如何进行重定向的? 您是否事先调用了HttpServletResponse.encodeRedirectURL()? 在这里阅读javadoc 您可以使用它像response.sendRedirect(response.encodeRedirectURL(path)); The issue was with the path in the JSESSIONID cookie. I still can't figure out why it was being set to the tomca

css:浮动div中重叠的标题h1(css: overlapping headlines h1 in floated divs)

我认为word-break ,如果你想在一个单词中打破行,你可以指定它,这样做可以解决问题: .column { word-break:break-all; } jsFiddle演示。 您可以在此处阅读有关word-break属性的更多信息。 I think word-break, with which you can specify if you want to break line within a word, will do the trick: .column { word-break

无论图像如何,Caffe预测同一类(Caffe predicts same class regardless of image)

我认为您忘记在分类时间内缩放输入图像,如train_test.prototxt文件的第11行所示。 您可能应该在C ++代码中的某个位置乘以该因子,或者使用Caffe图层来缩放输入(请查看ELTWISE或POWER图层)。 编辑: 在评论中进行了一次对话之后,结果发现在classification.cpp文件中错误地删除了图像均值,而在原始训练/测试管道中没有减去图像均值。 I think you have forgotten to scale the input image during cl

xcode语法颜色编码解释?(xcode syntax color coding explained?)

转到: Xcode => Preferences => Fonts & Colors 您将看到每个语法高亮颜色旁边都有一个简短的解释。 Go to: Xcode => Preferences => Fonts & Colors You'll see that each syntax highlighting colour has a brief explanation next to it.

在Access 2010 Runtime中使用Office 2000校对工具(Use Office 2000 proofing tools in Access 2010 Runtime)

你考虑过第三方拼写检查吗? 您可以将在C#中开发的自定义WinForms控件插入访问数据库吗? VB6控件怎么样? 如果你能找到一个使用第三方库进行拼写检查的控件,那可能会有效。 Have you considered a third party spell checker? Can you insert a custom WinForms controls developed in C# into an access database? What about a VB6 control? If

从单独的Web主机将图像传输到服务器上(Getting images onto server from separate web host)

我有同样的问题,因为我在远程服务器上有两个图像,我需要在每天的预定义时间复制到我的本地服务器,这是我能够提出的代码... try { if(@copy('url/to/source/image.ext', 'local/absolute/path/on/server/' . date("d-m-Y") . ".gif")) { } else { $errors = error_get_last(); throw new Exception($err

从旧版本复制文件并保留它们(旧/新版本)(Copy a file from old revision and keep both of them (old / new revision))

我不确定我完全明白你在说什么。 你能编辑你的帖子并包含你正在做的Subversion命令/操作的特定顺序吗? 最好使用命令行svn客户端,以便容易为其他人重现问题。 如果您只是想获取文件的旧副本(即使该文件不再存在),您可以使用如下命令: svn copy ${repo}/trunk/moduleA/file1@${rev} ${repo}/trunk/moduleB/file1 其中${repo}是您的存储库的URL, ${rev}是您想要的文件的版本。 这将恢复该文件的旧版本,包括最高版本