Foreach loop - Biblioteka.sk

Upozornenie: Prezeranie týchto stránok je určené len pre návštevníkov nad 18 rokov!
Zásady ochrany osobných údajov.
Používaním tohto webu súhlasíte s uchovávaním cookies, ktoré slúžia na poskytovanie služieb, nastavenie reklám a analýzu návštevnosti. OK, súhlasím


Panta Rhei Doprava Zadarmo
...
...


A | B | C | D | E | F | G | H | CH | I | J | K | L | M | N | O | P | Q | R | S | T | U | V | W | X | Y | Z | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9

Foreach loop
 ...
foreach loops are almost always used to iterate over items in a sequence of elements.

In computer programming, foreach loop (or for-each 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[1] 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.

The foreach statement in some languages has some defined order, processing each item in the collection from the first to the last. The foreach statement in many other languages, especially array programming languages, does not have any particular order. This simplifies loop optimization in general and in particular allows vector processing of items in the collection concurrently.

Syntax

Syntax varies among languages. Most use the simple word for, roughly as follows:

for each item in collection:
  do something to item

Language support

Programming languages which support foreach loops include ABC, ActionScript, Ada, C++11, C#, ColdFusion Markup Language (CFML), Cobra, D, Daplex (query language), Delphi, ECMAScript, Erlang, Java (since 1.5), JavaScript, Lua, Objective-C (since 2.0), ParaSail, Perl, PHP, Prolog,[2] Python, R, REALbasic, Rebol,[3] Red,[4] Ruby, Scala, Smalltalk, Swift, Tcl, tcsh, Unix shells, Visual Basic (.NET), and Windows PowerShell. Notable languages without foreach are C, and C++ pre-C++11.

ActionScript 3.0

ActionScript supports the ECMAScript 4.0 Standard[5] for for each .. in[6] which pulls the value at each index.

var foo:Object = {
	"apple":1,
	"orange":2
};

for each (var value:int in foo) { 
	trace(value); 
}

// returns "1" then "2"

It also supports for .. in[7] which pulls the key at each index.

for (var key:String in foo) { 
	trace(key); 
}

// returns "apple" then "orange"

Ada

Ada supports foreach loops as part of the normal for loop. Say X is an array:

for I in X'Range loop
   X (I) := Get_Next_Element;
end loop;

This syntax is used on mostly arrays, but will also work with other types when a full iteration is needed.

Ada 2012 has generalized loops to foreach loops on any kind of container (array, lists, maps...):

for Obj of X loop
   -- Work on Obj
end loop;

C

The C language does not have collections or a foreach construct. However, it has several standard data structures that can be used as collections, and foreach can be made easily with a macro.

However, two obvious problems occur:

  • The macro is unhygienic: it declares a new variable in the existing scope which remains after the loop.
  • One foreach macro cannot be defined that works with different collection types (e.g., array and linked list) or that is extensible to user types.

C string as a collection of char

#include <stdio.h>

/* foreach macro viewing a string as a collection of char values */
#define foreach(ptrvar, strvar) \
char* ptrvar; \
for (ptrvar = strvar; (*ptrvar) != '\0'; *ptrvar++)

int main(int argc, char** argv) {
 char* s1 = "abcdefg";
 char* s2 = "123456789";
 foreach (p1, s1) {
  printf("loop 1: %c\n", *p1);
 }
 foreach (p2, s2) {
  printf("loop 2: %c\n", *p2);
 }
 return 0;
}

C int array as a collection of int (array size known at compile-time)

#include <stdio.h>

/* foreach macro viewing an array of int values as a collection of int values */
#define foreach(intpvar, intarr) \
int* intpvar; \
for (intpvar = intarr; intpvar < (intarr + (sizeof(intarr)/sizeof(intarr))); ++intpvar)

int main(int argc, char** argv) {
 int a1 = {1, 1, 2, 3, 5, 8};
 int a2 = {3, 1, 4, 1, 5, 9};
 foreach (p1, a1) {
  printf("loop 1: %d\n", *p1);
 }
 foreach (p2, a2) {
  printf("loop 2: %d\n", *p2);
 }
 return 0;
}

Most general: string or array as collection (collection size known at run-time)

idxtype can be removed and typeof(col) used in its place with GCC
#include <stdio.h>
#include <string.h>

/* foreach macro viewing an array of given type as a collection of values of given type */
#define arraylen(arr) (sizeof(arr)/sizeof(arr))
#define foreach(idxtype, idxpvar, col, colsiz) \
idxtype* idxpvar; \
for (idxpvar = col; idxpvar < (col + colsiz); ++idxpvar)

int main(int argc, char** argv) {
 char* c1 = "collection";
 int c2 = {3, 1, 4, 1, 5, 9};
 double* c3;
 int c3len = 4;
 c3 = (double*)calloc(c3len, sizeof(double)); 
 c3 = 1.2; c3 = 3.4; c3 = 5.6; c3 = 7.8;

 foreach (char, p1, c1, strlen(c1)) {
  printf("loop 1: %c\n", *p1);
 }
 foreach (int, p2, c2, arraylen(c2)) {
  printf("loop 2: %d\n", *p2);
 }
 foreach (double, p3, c3, c3len) {
  printf("loop 3: %.1lf\n", *p3);
 }
 return 0;
}

C#

In C#, assuming that myArray is an array of integers:

foreach (int x in myArray) { Console.WriteLine(x); }

Language Integrated Query (LINQ) provides the following syntax, accepting a delegate or lambda expression:

myArray.ToList().ForEach(x => Console.WriteLine(x));

C++

C++11 provides a foreach loop. The syntax is similar to that of Java:

#include <iostream>

int main()
{
  int myint = {1, 2, 3, 4, 5};

  for (int i : myint)
  {
    std::cout << i << '\n';
  }
}

C++11 range-based for statements have been implemented in GNU Compiler Collection (GCC) (since version 4.6), Clang (since version 3.0) and Visual C++ 2012 (version 11 [8])

The range-based for is syntactic sugar equivalent to:

  for (auto __anon = begin(myint); __anon != end(myint); ++__anon)
  {
    auto i = *__anon;
    std::cout << i << '\n';
  }

The compiler uses argument-dependent lookup to resolve the begin and end functions.[9]

The C++ Standard Library also supports for_each,[10] that applies each element to a function, which can be any predefined function or a lambda expression. While range-based for is only from the start to the end, the range or direction can be changed by altering the first two parameters.

#include <iostream>
#include <algorithm> // contains std::for_each
#include <vector>

int main()
{
  std::vector<int> v {1, 2, 3, 4, 5};

  std::for_each(v.begin(), v.end(), (int i)
  {
    std::cout << i << '\n';
  });

  std::cout << "reversed but skip 2 elements:\n";

  std::for_each(v.rbegin()+2, v.rend(), (int i)
  {
    std::cout << i << '\n';
  });
}

Qt, a C++ framework, offers a macro providing foreach loops[11] using the STL iterator interface:

#include <QList>
#include <QDebug>

int main()
{
  QList<int> list;

  list << 1 << 2 << 3 << 4 << 5;

  foreach (int i, list)
  {
    qDebug() << i;
  }
}

Boost, a set of free peer-reviewed portable C++ libraries also provides foreach loops:[12]

#include <boost/foreach.hpp>
#include <iostream>
 
int main()
{
  int myint = {1, 2, 3, 4, 5};
 
  BOOST_FOREACH(int &i, myint)
  {
    std::cout << i << '\n';
  }
}

C++/CLI

The C++/CLI language proposes a construct similar to C#.

Assuming that myArray is an array of integers:

for each (int x in myArray)
{
    Console::WriteLine(x);
}

ColdFusion Markup Language (CFML)

Script syntax

// arrays
Zdroj:https://en.wikipedia.org?pojem=Foreach_loop
Text je dostupný za podmienok Creative Commons Attribution/Share-Alike License 3.0 Unported; prípadne za ďalších podmienok. Podrobnejšie informácie nájdete na stránke Podmienky použitia.






Text je dostupný za podmienok Creative Commons Attribution/Share-Alike License 3.0 Unported; prípadne za ďalších podmienok.
Podrobnejšie informácie nájdete na stránke Podmienky použitia.

Your browser doesn’t support the object tag.

www.astronomia.sk | www.biologia.sk | www.botanika.sk | www.dejiny.sk | www.economy.sk | www.elektrotechnika.sk | www.estetika.sk | www.farmakologia.sk | www.filozofia.sk | Fyzika | www.futurologia.sk | www.genetika.sk | www.chemia.sk | www.lingvistika.sk | www.politologia.sk | www.psychologia.sk | www.sexuologia.sk | www.sociologia.sk | www.veda.sk I www.zoologia.sk