c++ uint , unsigned int , int

穿精又带淫゛_ 提交于 2020-08-22 07:15:21

问题


Hi I have a program that deals alot with vectors and indexes of the elements of these vectors, and I was wondering:

  1. is there a difference between uint and unsigned int
  2. which is better to use one of the above types or just use int as I read some people say compiler does handle int values more efficiently, but if I used int I will have to check always for negative idxs which is pain.
  3. do you think iterators to be better? is it more efficient than normal indexing vectorx[idx]?

p.s the software will handle large data processes and good performance is a must have requirement


回答1:


  1. C++ defines no such type as uint. This must be "your" type, i.e. a type defined in your code or some third party library. One can guess that it is the same as unsigned int. Could be unsigned long int though or something else. Anyway, you have to check it yourself.

  2. It is a matter of personal style. I, for example, believe that one has to use unsigned types to represent naturally non-negative values, like sizes or quantities. There's no difference in performance between signed and unsigned types, aside from some specific contexts. I would say that in most cases it is unsigned types that will be handled more efficiently.

  3. Iterators make implementations more generic, i.e. you can use sequential-access iterator and thus make your implementation applicable to any sequential data structure. By using index you impose the random-access requirement on the data structure, which is a strong requirement. It is not a good idea to impose strong requirements when there's no real need for them.




回答2:


If you're looping through the vector sequentially, by all means, use the iterator. There is overhead related to indexing, regardless of the index type, which can be avoided by iterating.




回答3:


1) uint = unsigned int, in fact uint is just a typedef for unsigned int (will be replaced by unsigned int on compile time).

2) If you want to add to your code some "security" go with uint, you'll avoid for sure negative values.

3) If you run through the vector sequentially, go with iterators, they are optimized for sequential looping (they are some kind of pointers).




回答4:


As other poster have noted, uint is probably a typedef for unsigned int If you're using Visual Studio, you can check that fact very quickly by pressing F12 while the text cursor is in uint to see its definition.



来源:https://stackoverflow.com/questions/3552094/c-uint-unsigned-int-int

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!