0

I have an error while trying to use std::map with my own class as value. The definition of the map is this:

 std::map<std::string,CCrossSection> Xsects;

This line compiles fine (so it kindo of works?)

Xsects[sectionId].m_vProfile.push_back(pt);

When I try to iterate over the map however:

for (std::map<std::string,CCrossSection>::iterator xs = Xsects.begin(); xs < Xsects.end(); xs++) {
    it->second.SaveFile(f);
}

It gives me multiple errors similar to this:

error C2784: 'bool std::operator <(const std::_Tree<_Traits> &,const std::_Tree<_Traits> &)' : could not deduce template argument for 'const std::_Tree<_Traits> &' from 'std::_Tree<_Traits>::iterator'
        with
        [
           _Traits=std::_Tmap_traits<std::string,CCrossSection,std::less<std::string>,std::allocator<std::pair<const std::string,CCrossSection>>,false>
        ]
        c:\program files\microsoft visual studio 9.0\vc\include\xtree(1466) : see declaration of 'std::operator <'

I thought that it is a problem with less operator and I added it to my definition of the class CCrossSection, but it didn't change a thing. Later I read that the key of the map has to have less operator defined and I think std::string has. Any ideas why it happens?

Cheers Tomek

  • Not sure but I think this is because you are doing xs < Xsects.end() instead of xs != Xsects.end() – Vincent Apr 29 '13 at 07:41
  • Based on Vincent's answer, I had a look at http://www.cplusplus.com/reference/iterator/iterator/ The operator '<' isn't defined for the Iterator base class, but the operator '!=' is. So Vincent is correct. – Jimbo Apr 29 '13 at 07:43

1 Answers1

3

it will compile when you compare the end iterator with operator!=

Serve Laurijssen
  • 9,266
  • 5
  • 45
  • 98
  • :- You are right. But here I have a question why `map` does not work with `<`? – Rasmi Ranjan Nayak Apr 29 '13 at 07:43
  • Incrementing past the end of any iterator is undefined behaviour, take a look at http://stackoverflow.com/questions/6673762/why-is-used-with-iterators – ed_me Apr 29 '13 at 07:46
  • It's nop `map`that doesn't work, it's the `iterator` that doesn't work with `operator<()`. – Axel Apr 29 '13 at 07:46
  • unlike eg a vector a map does not necessarily order its objects in memory from low to high so operator< does not work for maps – Serve Laurijssen Apr 29 '13 at 07:48
  • 2
    The precise answer: `operator<` works for random-access iterators. Those support `operator+` and `operator-` as well, and `iterA – MSalters Apr 29 '13 at 07:53
  • Yes! It does compile. Hitherto I've used vectors only and < worked for iterators. How am I supposed to deduce this from 47 stl error messages is beyound my comprehension though :) – user1711690 Apr 29 '13 at 08:16