-2

Below is a simplified code to replicate my problem:

Working code:

int main(int argc, char **argv)
{
    std::vector<int> x;
    std::map<char, std::vector<int>::size_type> y;
    y[0]=x.size();
    return 0;
}

Not working code (using decltype):

int main(int argc, char **argv)
{
    std::vector<int> x;
    //std::map<char, std::vector<int>::size_type> y;
    std::map<char, decltype(x.begin())> y;
    y[0]=x.size();
    return 0;
}

The code fails to compile with the following error:

error: no match for ‘operator=’ (operand types are ‘std::map > >::mapped_type {aka __gnu_cxx::__normal_iterator >}’ and ‘std::vector::size_type {aka long unsigned int}’) y[0]=x.size();

Shouldn't decltype(x.begin()) be equivalent to std::vector<int>::size_type?

  • 2
    `x.begin()` is an iterator and `x.size()` isnt, so no, they are not equivalent – 463035818_is_not_an_ai Jul 13 '17 at 08:20
  • You do know that [`begin`](http://en.cppreference.com/w/cpp/container/vector/begin) returns an *iterator* and not an integer which is what [`size`](http://en.cppreference.com/w/cpp/container/vector/size) returns? Perhaps you should take a few steps back and [find a good beginners book](http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and start over? – Some programmer dude Jul 13 '17 at 08:20
  • 5
    would be really interesting to know why you think they are equivalent. I mean already your title says that it is an iterator... – 463035818_is_not_an_ai Jul 13 '17 at 08:22
  • Looking at some reference for [`begin`](http://en.cppreference.com/w/cpp/container/vector/begin) and [`size`](http://en.cppreference.com/w/cpp/container/vector/size) would have told you their return types differ. – Angew is no longer proud of SO Jul 13 '17 at 08:29
  • @tobi303 I guess I was used to do stuff like `it - vec.begin()` to get the current index the iterator is pointing to. I guess some implicit casting is happening here – Jafar Qutteineh Jul 13 '17 at 09:03
  • @JafarQutteineh no, there is no implicit casting, it is just that `iterator::operator-` typically returns an integer, but iterators themself arent integers – 463035818_is_not_an_ai Jul 13 '17 at 09:14
  • @tobi303 Thanks, it's very clear now! – Jafar Qutteineh Jul 13 '17 at 09:15

1 Answers1

3

Shouldn't decltype(x.begin()) be equivalent to std::vector<int>::size_type?

No, what std::vector::begin returns is std::vector<T>::iterator.

I suppose what you want would be decltype(x.size()).

songyuanyao
  • 169,198
  • 16
  • 310
  • 405