Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map implementation differs between linux and windows

The following code acts differently after being compiled in linux and Visual Studio 2015.

#include <map>
#include <iostream>
using namespace std;

int main(void)
{
    map<int, int> map1;
    int keyCount = 2;

    for (int i = 0; i < keyCount; i++)
    {
        map1[i] = map1.size();
    }

for (auto value : map1) 
    {
        cout << "key: " << value.first << " value: " << value.second << endl;
    }
return 0;
}

The result in Visual Studio :

key: 0 value: 0
key: 1 value: 1

The result in linux compiled with g++ -std=c++11 -Wall -pedantic

key: 0 value: 1
key: 1 value: 2

I have two questions:

  1. As far as I understand c++, the VS implementation is right.
    If I change the code to:

    for (int i=0; i < keyCount; i++)
    {
        unsigned int mapSize= map1.size();
        map1[i] = mapSize; 
    }
    

then it behaves like Visual Studio on both platforms.
Shouldn't the code always behave like this?

2.What Visual Studio compiler settings can I use to make sure that VS will compile the same as Linux?
I am working on Windows, but have an assignment that must work on Linux.

like image 227
lazy traveller Avatar asked Apr 08 '17 19:04

lazy traveller


1 Answers

map1[i] = map1.size();

expands to

(map1.operator[](i)) = (map1.size());

C++ makes no guarantees about whether operator[] or size is called first, since both are operands to the assignment expression. Both compilers are correct.

You should split your expression into two statements if you expect one behavior or the other.

like image 93
aschepler Avatar answered Sep 28 '22 11:09

aschepler