This topic is now archived and is closed to further replies.

Hopefully my last STL dumb question.

This topic is 4944 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Here's a toy example. Say I have a std::vector of points. that, themselves, contain an index 'i'. I map pointers to those points together with pointers to those points index. Shouldn't the map remain sorted with the new index if I modify it AFTER having inserted them in the list ? My functor is ok, and if I switch the index switching code BEFORE the insertion in the map, it works fine.
#include <iostream>
#include <vector>
#include <map>
#include <algorithm>

struct ltind
  bool operator()(const int* a, const int* b) const
	return (*a) < (*b);

struct Point {
	int i;
	int x;
	int y;
	Point(int _i, int _x, int _y) { i= _i; x = _x; y=_y;}

int main() {
	std::vector<Point> test;
	std::multimap<int*, Point*, ltind> zeList;
        zeList.insert(std::pair<int*, Point*>(&(test[0].i),&test[0]));
	zeList.insert(std::pair<int*, Point*>(&(test[1].i),&test[1]));
	zeList.insert(std::pair<int*, Point*>(&(test[2].i),&test[2]));
	test[0].i = 3;
	test[1].i = 2;
	test[2].i = 1;
	for (std::multimap<int*, Point*, ltind>::iterator it = zeList.begin(); it != zeList.end(); ++it) {
		std::cout << "  [" << *it->first << ", (" << (*it).second->x << "," << (*it).second->y << ")]" << std::endl;

	return 0;
While the output should be [1, (3,3)] [2, (2,2)] [3, (1,1)] It is actually [3, (1,1)] [2, (2,2)] [1, (3,3)] I must be doing something wrong yet I can't find it. [edited by - xMcBaiNx on May 29, 2004 2:53:59 PM]

Share this post

Link to post
Share on other sites
std::map and std::multimap expect the logical value of the indexers to be immutable, which is why they declare the value type of the key to be const. When you use a pointer as a key type, you subvert the logical constness of the key. Don''t do that. If you need to change the key in a std::map, delete the node and reinsert it.

Share this post

Link to post
Share on other sites
Hmm.. Guess I had skipped the const keyword eh?

The problem however, since it is a multimap, is that there might be a lot of entries with the same key. That makes it impossible to find the right one back unless i loop trough those with the said key to compare the pointers. That makes it kindof slow...

Well I might do this. We''ll see.


Share this post

Link to post
Share on other sites