In object-oriented programming, an indexer allows instances of a particular class or struct to be indexed just like arrays. [1] It is a form of operator overloading.
In C++ one can emulate indexing by overloading the []
operator. The expression a[b...]
translates to a call to the user-defined function operator[]
as (a).operator[](b...)
. [2] Here is an example,
structvector{intsize;double*data;vector(intn){size=n;data=newdouble[n]();}~vector(){size=0;delete[]data;}double&operator[](inti){returndata[i];}};#include<iostream>intmain(){vectorv(3);for(inti=0;i<v.size;i++)v[i]=i+1;for(inti=0;i<v.size;i++)std::cout<<v[i]<<"\n";return0;}
Indexers are implemented through the get and set accessors for the operator[]
. They are similar to properties, but differ by not being static, and the fact that indexers' accessors take parameters. The get and set accessors are called as methods using the parameter list of the indexer declaration, but the set accessor still has the implicit value
parameter.
publicclassVector{privatedouble[]data;publicVector(intn){data=newdouble[n];}publicintsize=>data.Length;publicdoublethis[inti]{get=>data[i];set=>data[i]=value;}publicstaticvoidMain(){varv=newVector(3);for(inti=0;i<v.size;i++)v[i]=i+1;for(inti=0;i<v.size;i++)System.Console.WriteLine(v[i]);}}
Here is a C# example of the usage of an indexer in a class: [3]
classFamily{privateList<string>_familyMembers=newList<string>();publicFamily(paramsstring[]members){_familyMembers.AddRange(members);}publicstringthis[intindex]{// The get accessorget=>_familyMembers[index];// The set accessor with set=>_familyMembers[index]=value;}publicintthis[stringval]{// Getting index by value (first element found)get=>_familyMembers.FindIndex(m=>m==val);}publicintLength=>_familyMembers.Count;}
Usage example:
voidMain(){vardoeFamily=newFamily("John","Jane");for(inti=0;i<doeFamily.Length;i++){varmember=doeFamily[i];varindex=doeFamily[member];// same as i in this case, but it demonstrates indexer overloading allowing to search doeFamily by value.Console.WriteLine($"{member} is the member number {index} of the {nameof(doeFamily)}");}}
In this example, the indexer is used to get the value at the nth position, and then to get the position in the list referenced by its value. The output of the code is:
John is the member number 0 of the doeFamily Jane is the member number 1 of the doeFamily
In PHP indexing can be implemented via the predefined ArrayAccess
interface, [4]
<?phpclassVectorimplementsArrayAccess{function__construct(int$n){$this->size=$n;$this->data=array_fill(0,$n,0);}publicfunctionoffsetGet($offset):mixed{return$this->data[$offset];}publicfunctionoffsetSet($offset,$value):void{$this->data[$offset]=$value;}publicfunctionoffsetExists($offset):bool{}publicfunctionoffsetUnset($offset):void{}}$v=newVector(3);for($i=0;$i<$v->size;$i++)$v[$i]=$i+1;for($i=0;$i<$v->size;$i++)print"{$v[$i]}\n";?>
In Python one implements indexing by overloading the __getitem__
and __setitem__
methods,
importarrayclassVector(object):def__init__(self,n):self.size=nself.data=array.array("d",[0.0]*n)def__getitem__(self,i):returnself.data[i]def__setitem__(self,i,value):self.data[i]=valuev=Vector(3)foriinrange(v.size):v[i]=i+1foriinrange(v.size):print(v[i])
Rust provides the std::ops::Index trait. [5]
usestd::ops::Index;enumNucleotide{A,C,G,T,}structNucleotideCount{a: usize,c: usize,g: usize,t: usize,}implIndex<Nucleotide>forNucleotideCount{typeOutput=usize;fnindex(&self,nucleotide: Nucleotide)-> &Self::Output{matchnucleotide{Nucleotide::A=>&self.a,Nucleotide::C=>&self.c,Nucleotide::G=>&self.g,Nucleotide::T=>&self.t,}}}letnucleotide_count=NucleotideCount{a: 14,c: 9,g: 10,t: 12};assert_eq!(nucleotide_count[Nucleotide::A],14);assert_eq!(nucleotide_count[Nucleotide::C],9);assert_eq!(nucleotide_count[Nucleotide::G],10);assert_eq!(nucleotide_count[Nucleotide::T],12);
In Smalltalk one can emulate indexing by (e.g.) defining the get:
and set:value:
instance methods. For example, in GNU Smalltalk,
Objectsubclass:vector [ |data| ] vectorclassextend [ new:n [ |v|v:=supernew.vinit:n.^v] ] vectorextend [ init:n [ data:=Arraynew:n ] ] vectorextend [ size [ ^(datasize) ] ] vectorextend [ get:i [ ^(dataat:i) ] ] vectorextend [ set:ivalue:x [ dataat:iput:x ] ] v:=vectornew:31to: (vsize) do: [:i|vset:ivalue: (i+1) ] 1to: (vsize) do: [:i| (vget:i) printNl ]
In computer science, an array is a data structure consisting of a collection of elements, of same memory size, each identified by at least one array index or key. An array is stored such that the position of each element can be computed from its index tuple by a mathematical formula. The simplest type of data structure is a linear array, also called a one-dimensional array.
In computer programming, lazy initialization is the tactic of delaying the creation of an object, the calculation of a value, or some other expensive process until the first time it is needed. It is a kind of lazy evaluation that refers specifically to the instantiation of objects or other resources.
Generic programming is a style of computer programming in which algorithms are written in terms of data types to-be-specified-later that are then instantiated when needed for specific types provided as parameters. This approach, pioneered in the programming language ML in 1973, permits writing common functions or data types that differ only in the set of types on which they operate when used, thus reducing duplicate code.
In object-oriented programming, the iterator pattern is a design pattern in which an iterator is used to traverse a container and access the container's elements. The iterator pattern decouples algorithms from containers; in some cases, algorithms are necessarily container-specific and thus cannot be decoupled.
In computer programming, an iterator is an object that progressively provides access to each item of a collection, in order.
Template metaprogramming (TMP) is a metaprogramming technique in which templates are used by a compiler to generate temporary source code, which is merged by the compiler with the rest of the source code and then compiled. The output of these templates can include compile-time constants, data structures, and complete functions. The use of templates can be thought of as compile-time polymorphism. The technique is used by a number of languages, the best-known being C++, but also Curl, D, Nim, and XL.
In computer programming, a function object is a construct allowing an object to be invoked or called as if it were an ordinary function, usually with the same syntax. In some languages, particularly C++, function objects are often called functors.
In computer programming, foreach loop is a control flow statement for traversing items in a collection. foreach is usually used in place of a standard for loop statement. Unlike other for loop constructs, however, foreach loops usually maintain no explicit counter: they essentially say "do this to everything in this set", rather than "do this x times". This avoids potential off-by-one errors and makes code simpler to read. In object-oriented languages, an iterator, even if implicit, is often used as the means of traversal.
In the Perl programming language, autovivification is the automatic creation of new arrays and hashes as required every time an undefined value is dereferenced. Perl autovivification allows a programmer to refer to a structured variable, and arbitrary sub-elements of that structured variable, without expressly declaring the existence of the variable and its complete structure beforehand.
A bit array is an array data structure that compactly stores bits. It can be used to implement a simple set data structure. A bit array is effective at exploiting bit-level parallelism in hardware to perform operations quickly. A typical bit array stores kw bits, where w is the number of bits in the unit of storage, such as a byte or word, and k is some nonnegative integer. If w does not divide the number of bits to be stored, some space is wasted due to internal fragmentation.
C++/CLI is a variant of the C++ programming language, modified for Common Language Infrastructure. It has been part of Visual Studio 2005 and later, and provides interoperability with other .NET languages such as C#. Microsoft created C++/CLI to supersede Managed Extensions for C++. In December 2005, Ecma International published C++/CLI specifications as the ECMA-372 standard.
Loop fission is a compiler optimization in which a loop is broken into multiple loops over the same index range with each taking only a part of the original loop's body. The goal is to break down a large loop body into smaller ones to achieve better utilization of locality of reference. This optimization is most efficient in multi-core processors that can split a task into multiple tasks for each processor.
String functions are used in computer programming languages to manipulate a string or query information about a string.
A class in C++ is a user-defined type or data structure declared with any of the keywords class
, struct
or union
that has data and functions as its members whose access is governed by the three access specifiers private, protected or public. By default access to members of a C++ class declared with the keyword class
is private. The private members are not accessible outside the class; they can be accessed only through member functions of the class. The public members form an interface to the class and are accessible outside the class.
sort is a generic function in the C++ Standard Library for doing comparison sorting. The function originated in the Standard Template Library (STL).
C++11 is a version of a joint technical standard, ISO/IEC 14882, by the International Organization for Standardization (ISO) and International Electrotechnical Commission (IEC), for the C++ programming language. C++11 replaced the prior version of the C++ standard, named C++03, and was later replaced by C++14. The name follows the tradition of naming language versions by the publication year of the specification, though it was formerly named C++0x because it was expected to be published before 2010.
In the C++ programming language, the assignment operator, =
, is the operator used for assignment. Like most other operators in C++, it can be overloaded.
This comparison of programming languages (associative arrays) compares the features of associative array data structures or array-lookup processing for over 40 computer programming languages.
Expression templates are a C++ template metaprogramming technique that builds structures representing a computation at compile time, where expressions are evaluated only as needed to produce efficient code for the entire computation. Expression templates thus allow programmers to bypass the normal order of evaluation of the C++ language and achieve optimizations such as loop fusion.
In computer science, array is a data type that represents a collection of elements, each selected by one or more indices that can be computed at run time during program execution. Such a collection is usually called an array variable or array value. By analogy with the mathematical concepts vector and matrix, array types with one and two indices are often called vector type and matrix type, respectively. More generally, a multidimensional array type can be called a tensor type, by analogy with the physical concept, tensor.
{{cite web}}
: CS1 maint: numeric names: authors list (link)