JP Morgan Interview Question
Field Salessincorrect, code below works
#include <iterator>
#include <map>
#include <iostream>
typedef std::map<int,int>::iterator m_t;
int main()
{
std::map<int,int> m;
m[1] = 1; m[2] = 2; m[3] = 3; m[4] = 4;
m[5] = 5; m[6] = 6; m[7] =7; m[8]=8;m[9]=9;
m[10] = 10; m[11]=11;
m_t it = m.begin();
for(; it != m.end(); ++it) m.erase(it++);
it = m.begin();
for(; it != m.end(); ++it) {
std::cout << it->first << " , " << it->second << std::endl;
}
}
Void eraseFunction(map<int,int> &x)
{
for(map<int,int>::iterator it = x.begin(); it != x.end(); ++it)
{
x.erase(it++);
}
}
void remove_mp_odd_index_elements(map<int,int>& a_map)
{
if( a_map.size() <= 1 )
return;
int elems_to_erase = a_map.size() / 2;
int k = 1;
map<int,int>::iterator it;
while( k <= elems_to_erase )
{
it = a_map.begin();
for(int j = 1; j<=k; j++)
it++;
a_map.erase(it); // an erase invalidates the iterator
k++;
}
}
void remove_mp_even_index_elements(map<int,int>& a_map)
{
if( a_map.size() == 1 )
{
a_map.clear();
return;
}
else if( a_map.size() == 2 ){
a_map.erase(a_map.begin());
return;
}
int elems_to_erase = a_map.size() / 2 + 1;
int k = 1;
map<int,int>::iterator it;
while( k <= elems_to_erase )
{
it = a_map.begin();
for(int j = 1; j<k; j++)
it++;
a_map.erase(it); // an erase invalidates the iterator
k++;
}
}
# I think that an "erase" invalidates all iterators
# attached on a container. Thus begin() and/or end must be
# called in order to have a valid set of iterators and
# remove the correct elements.
erasing an element of map in for loop erases every alternative element.
map<int, int> mymap;
for(map<int, int>::iterator it = mymap.begin(); it != mymap.end(); ++it )
{
mymap.erase(it);
}
ig mymap have 10 element, above code erases only 5
void eraseFunction(map<int,int> &x)
{
map<int,int>::iterator k;
for(map<int,int>::iterator it = x.begin(); it != x.end();)
{
k = it;
it++;
if(it==x.end()) {
cout <<"Erasing "<< " [" << (*k).first << ", " << (*k).second << "]" << endl;
x.erase(k);
break;
}
it++;
cout <<"Erasing "<< " [" << (*k).first << ", " << (*k).second << "]" << endl;
x.erase(k);
}
}
This will work....
#include <iostream>
#include <algorithm>
#include <set>
int main() {
std::set<int> myset;
for (int i = 0; i < 10; ++i) myset.insert(i*10);
std::cout << "before " << std::endl;
std::for_each(myset.begin(), myset.end(), [](int n) {std::cout << n << std::endl; });
std::set<int>::iterator it = myset.begin();
int n = 0;
while (it != myset.end()) {
if (n % 2 == 1) {
myset.erase(it++);
}
else {
++it;
}
n++;
}
std::cout << "after " << std::endl;
std::for_each(myset.begin(), myset.end(), [](int n) {std::cout << n << std::endl; });
std::cout << "press enter to continue ..." << std::endl;
std::cin.get();
return 0;
}
for ( it=xmap.begin(), int i=0; it != xmap.end(); it++, i++ )
- topofmyhead July 10, 2011{
if ( i % 2)
{
mymap.erase (it);
}
}