I have an object outside of the for-each loops that contains a static vector of pair. I want to increment the second parameter of the pair, as the code below shows. However, when I print the second parameter from within another for-each loop, it prints '0' as the value for all elements in the vector. But if I print from within the first for-each loop, it prints '1', as intended.
I do not understand why the value would not be saved after the change. I have looked it up and the for-each allows me to change the value, as well as the pair.
char[] name = "abcde";
for(int i =0;i<5;i++){
std::pair <string, int> pairCounter;
pairCounter = make_pair(name[i], 0);
outside::lstPairCounter.push_back(pairCounter);
}
for each (pair<string,int> counter in outside::lstPairCounter){
counter.second++;
}
for each (pair<string,int> counter in outside::lstPairCounter){
cout<<counter.second<<'\n';
}
The for-each loop below cannot change the values in the array because only the loop variable value will change.
forEach() does not mutate the array on which it is called.
Foreach loop is used to iterate over the elements of a containers (array, vectors etc) quickly without performing initialization, testing and increment/decrement. The working of foreach loops is to do something for every element rather than doing something n times.
Introduction. The foreach loop in C++ or more specifically, range-based for loop was introduced with the C++11. This type of for loop structure eases the traversal over an iterable data set. It does this by eliminating the initialization process and traversing over each and every element rather than an iterator.
Don't use
for each
preferrably (see https://msdn.microsoft.com/en-us/library/ms177202.aspx), as it is non-standard.
Here's how a for each loop in C++11 works:
std::vector<int> v{1,2,3,4,5};
// i becomes a COPY of each value in v, i.e. no changes occur in v
for(int i : v)
++i;
// i becomes a reference to the values in v, changes DO occur in v
for(int& i : v)
++i;
// you could also take a const-reference, good for expensive-to-copy types
for(const T& t: other_vector)
// do stuff
Take element by reference instead of value:
for (std::pair<string,int>& counter : outside::lstPairCounter){
counter.second++;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With