for each question

hi every body . i read c++11 and i have one question . i use "visual studio 2010 sp1" and i want use "for each" statement in "win32 console app" .

1
2
3
4
vector<int> v(10);
for each (int &i in v) {

}


why this code is wrong ?!! the compiler take error can not convert constant ! i think before i was install sp1 that code compile successfuly but when i install sp1 compiler take error.
tnx alot
I guess you mean the range-based for-loop. Remove each and replace in with :.
1
2
3
4
vector<int> v(10);
for (int &i : v) {

}
MS VC++ 2010 does not support the range-based for statement.
EDIT: I wanted to say that the C++ 2011 standard range-based for statement is not supported in MS VC++ 2010.
However you can use a MS VC++ 2010 language extension regarding to for statement. For example

1
2
3
4
5
6
7
8
9
{
	int a[] = { 1, 2, 3 };
	for each ( int x in a ) { std::cout << x << ' '; }
	std::cout << std::endl;

	std::vector<int> v( a, a + 3 );
	for each ( int x in v ) { std::cout << x << ' '; }
	std::cout << std::endl;
}
Last edited on
tnx but i want initialize elements i want use reference "int &" ! please see my question
Either upgrade your compiler to Visual Studio 2012 or install boost (from http://boostpro.com ) although boost did it in ALL CAPS.

Last edited on
:D it isnt my problem !! if some body know please help me
for each is a microsoft extension for CLI:

http://msdn.microsoft.com/en-us/library/ms177202.aspx

you probably need to enable 'Common Runtime Language' support
for each statement in visula 2008 only works for CLI but in vs 2010 and 2012 works for console application and you can use of it in your code like range-base loop. range base loop works only for vs 2012 . in vs 2010 we dont have range base loop instead we have for each statement :
1
2
3
4
vector<int> v;
...
for each (int i in v)
     cout << i;

this code works correctly but i want initialize element :
1
2
3
4
vector<int> v;
...
for each (int &i in v)
     i *= 10;

that take error if you compile it . my question is how to compile above code ?!!
In MS C++/CLI the for each may not change elements of a sequence. So references are not allowed except const references.
you are in wrong . we can initialize for example :
1
2
3
int a[10];
for each (int &i in a)
     i += 10;


this code is true but in vector or other container and tr1::array doesnt work !
i think i cant solve my problem and for each doesnt work for them but im not sure
I took into account that in C# foreach statement uses read-only variable.

The type and identifier of a foreach statement declare the iteration variable of the statement. The iteration variable corresponds to a read-only local variable with a scope that extends over the embedded statement.


However it seems that in MS C++ the corresponding for each statement has its own semantic. You should look through MSDN.
Last edited on
ok tnx alot
Topic archived. No new replies allowed.