私はCを学習しています。私は配列の値をリストしたいと思います。 PHPでCでの配列のリスト
:
$arr = array("laguna", "megane", "clio");
foreach($arr as $no => $name)
{
echo $no.") ".$name;
}
/*
Output :
0) Laguna
1) Megane
2) Clio
*/
どのように私はそれがCで行うことができますか?
私はCを学習しています。私は配列の値をリストしたいと思います。 PHPでCでの配列のリスト
:
$arr = array("laguna", "megane", "clio");
foreach($arr as $no => $name)
{
echo $no.") ".$name;
}
/*
Output :
0) Laguna
1) Megane
2) Clio
*/
どのように私はそれがCで行うことができますか?
C
char* arr[] = {"laguna","megane","clio",NULL};
for(int i = 0; arr[i]; i++)
{
printf("%d) %s\n",i,arr[i]);
}
注:OPの質問は、もともとC++としてタグ付けされたので、あなたが内部のfor_each
アルゴリズムを使用することができます
C++具体的な方法について興味があるかもしれない人のため-であるように私はこの答えを残しておきますalgorithm
...逆参照が可能で、段階的に介入できる(つまり、operator++
をサポートする)すべてのオブジェクトで動作します。 for_each
アルゴリズム
入力引数を使用するなど、std::vector
ようなものを指すポインタまたはイテレータをSTLコンテナを使用している場合、配列またはコンテナオブジェクトの先頭を指すポインタ(またはイテレータ)でありますオブジェクトの終わりを過ぎてから、配列やコンテナの各メンバに適用される関数を定義します。例えば
:
#include <algorithm>
#include <iostream>
using namespace std;
int array[] = { 1, 2, 3, 4, 5 };
//pointer to the start of the array
int* start = array;
//pointer to one position past the end of the array
int* end = array + sizeof(array)/sizeof(int);
//function applied to each member of the array
void function(int a)
{
static int count = 0;
cout << "Value[" << count++ << "]: " << a << endl;
}
//call the for_each algorithm
for_each(start, end, function);
C及びC++では、同じ言語ではありません。最近のC++方言でC++ std::vectorを使用して、(未テストコード)を試してみてください:
std::vector<std::string> vecstr;
vecstr.push_back("laguna");
vecstr.push_back("megane");
for (std::vector<std::string>::iterator it= vecstr.begin();
it != vecstr.end(); it++)
std::out << *it << std::endl;
これはあなたにC++での配列を使用してよく見て与えます。
// arrays example
#include <iostream>
using namespace std;
int billy [] = {16, 2, 77, 40, 12071};
int n, result=0;
int main()
{
for (n=0 ; n<5 ; n++)
{
result += billy[n];
}
cout << result;
return 0;
}
あなたは一歩進んで、setとmapのようなSTLコンテナを使用できます。 C言語で http://ideone.com/U62Q8
ああ。今質問は編集されました! – King
:
#include <stdio.h>
int array[6]= { 1, 2, 3, 4, 5, 6 };
void main() {
int len=sizeof(array)/sizeof(int);
int i;
for(i=0;i<len;i++)
{
printf("Elements in position :%d :%d ",i,array[i]);
}
}
#include <stdio.h>
int main(){
char *arr[] = {"laguna", "megane", "clio", NULL};
char **name = arr;
while(*name){
int no = name - arr;
printf("%d) %s\n", no, *name++);
}
return 0;
}
CまたはC++? –
を選択する必要があります。OK Cを選択しています。 – Eray