"double" index for vector

Jan 27, 2015 at 6:26am
I read in my book that im reading that u cant give non integer indexes to vectors and it makes sence, but i checked it out and i got answer 14 starting from index 3.0000001 and ending with 3.99. Why is this so?

1
2
3
4
5
6
7
8
9
10
#include <iostream>
#include <vector>
using namespace std;

int main(){

	vector<int> list{ 2, 3, 1, 14, 4 };
	int a = list[3.99];
	cout << a << endl;
}
Jan 27, 2015 at 6:42am
closed account (SECMoG1T)
3.99 because vector indices must be of integral types, you floating point value 3.99 will be auto converted to an integral value , hence 3.99 will be converted to 3 an integer



If the conversion is from a floating-point type to an integer type, the value is truncated (the 
decimal part is removed). If the result lies outside the range of representable values by the 
type, the conversion causes undefined behavior.


http://www.cplusplus.com/doc/tutorial/typecasting/
http://en.cppreference.com/w/cpp/language/implicit_cast
Last edited on Jan 27, 2015 at 6:53am
Jan 27, 2015 at 7:01am
TY a lot for your help man :) I was hoping to get some error with this code so was confused :D
Topic archived. No new replies allowed.