I have this code here. It's a weird unordered_map of string
to vector<string>
. Why does the memory location of the older strings change with each push_back
to the vector?
The I tried the same thing on an unordered_map<string, vector<int>>
, and the memory locations of the ints in the vector of ints did NOT exhibit the same behavior, i.e. with each push_back, the older ints did not change their memory location. I originally though it's because ints are smaller than strings memory-wise, but pushing back 50 ints still do not change the memory location. Why is there such a difference?
This is compiled on a MacOS, with the clang version of Apple LLVM version 7.3.0 (clang-703.0.31). This happens regardless if I compile with the c++11 flag or not.
#include <unordered_map>
#include <iostream>
#include <vector>
using namespace std;
int main() {
unordered_map<string, vector<string> > kvStore;
kvStore["a"] = vector<string>();
cout << "kvStore mem location: " << &(kvStore) << endl;
cout << "kvStore[a] mem location: " << &(kvStore["a"]) << endl;
cout << endl;
cout << "--1st push_back--" << endl;
kvStore["a"].push_back("foo");
cout << "kvStore mem location: " << &(kvStore) << endl;
cout << "kvStore[a] mem location: " << &(kvStore["a"]) << endl;
cout << "kvStore[a][0] mem location: " << &(kvStore["a"][0]) << endl;
cout << endl;
cout << "--2nd push_back--" << endl;
kvStore["a"].push_back("bar");
cout << "kvStore mem location: " << &(kvStore) << endl;
cout << "kvStore[a] mem location: " << &(kvStore["a"]) << endl;
cout << "kvStore[a][0] mem location: " << &(kvStore["a"][0]) << endl;
cout << "kvStore[a][1] mem location: " << &(kvStore["a"][1]) << endl;
cout << endl;
cout << "--3rd push_back--" << endl;
kvStore["a"].push_back("foobar");
cout << "kvStore mem location: " << &(kvStore) << endl;
cout << "kvStore[a] mem location: " << &(kvStore["a"]) << endl;
cout << "kvStore[a][0] mem location: " << &(kvStore["a"][0]) << endl;
cout << "kvStore[a][1] mem location: " << &(kvStore["a"][1]) << endl;
return 0;
}
Aucun commentaire:
Enregistrer un commentaire