-2

I don't know about the vector class of int but why this code is not showing ArrayIndexOutOfBounds error like java.

for(int i = 0; i < nums.size(); i++) {
    if(nums[i] == nums[i+1])
        i++;
    else            
        ret.push_back(nums[i]);        
}
sweenish
  • 4,793
  • 3
  • 12
  • 23
  • is this a c++ question? – Stultuske Aug 23 '21 at 13:33
  • 5
    C++ is not Java is the simplest answer. – sweenish Aug 23 '21 at 13:33
  • C++ is not Java. In C++, when you attempt to access a nonexistent array or vector element through the [] [operator](https://en.cppreference.com/w/cpp/container/vector/operator_at) the result is _undefined behavior_. That means anything at all is valid behavior as far as the language is concerned. Throwing an exception, reading garbage from memory, segfaulting, appearing to work as though your code was correct--all equally valid results from C++'s perspective. – Nathan Pierson Aug 23 '21 at 13:34
  • If you are using [`vector`](https://en.cppreference.com/w/cpp/container/vector)s then [`operator[]`](https://en.cppreference.com/w/cpp/container/vector/operator_at) does not perform bounds checking. Use [`vector::at(size_t)`](https://en.cppreference.com/w/cpp/container/vector/at) instead – Lala5th Aug 23 '21 at 13:36
  • This should be of use: https://stackoverflow.com/q/388242/2079303 – eerorika Aug 23 '21 at 13:38
  • The implementations can be extremely varied between Java and C++. They are not the same language (for one issue, they have different containers and the containers are implemented differently). – Thomas Matthews Aug 23 '21 at 16:38

1 Answers1

1

See the documentation for the operator[] for std::vector:

No bounds checking is performed.

and

Accessing a nonexistent element through this operator is undefined behavior.

The alternative, with bounds checking, is the at function, which can throw a std::out_of_range exception. Using this function is safer, but also slightly slower.

Here, it appears that Java prioritizes safety whereas C++ leaves the choice up to the programmer.

Yun
  • 3,056
  • 6
  • 9
  • 28