Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing value in a pair from foreach doesn't show change out of loop

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';

}
like image 709
user3812584 Avatar asked Mar 26 '15 21:03

user3812584


People also ask

Can you change values in a for-each loop?

The for-each loop below cannot change the values in the array because only the loop variable value will change.

Does foreach modify the original array?

forEach() does not mutate the array on which it is called.

How does for-each loop work in c++?

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.

Is there a foreach in c++?

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.


2 Answers

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
like image 146
jensa Avatar answered Sep 20 '22 16:09

jensa


Take element by reference instead of value:

for (std::pair<string,int>& counter : outside::lstPairCounter){
    counter.second++;
}
like image 21
Jarod42 Avatar answered Sep 21 '22 16:09

Jarod42