惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

爱范儿
爱范儿
腾讯CDC
博客园 - 司徒正美
A
About on SuperTechFans
H
Help Net Security
J
Java Code Geeks
C
Check Point Blog
B
Blog RSS Feed
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
MongoDB | Blog
MongoDB | Blog
U
Unit 42
Hugging Face - Blog
Hugging Face - Blog
Last Week in AI
Last Week in AI
MyScale Blog
MyScale Blog
V
Visual Studio Blog
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
I
InfoQ
H
Hackread – Cybersecurity News, Data Breaches, AI and More
F
Fortinet All Blogs
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
GbyAI
GbyAI
博客园 - 【当耐特】
雷峰网
雷峰网

jdhao's digital space

Conversion between base64 and OpenCV or PIL Image 腾讯云对象存储博客图床开启 CDN 加速(不需要购买额外域名) Search and Replace in Multiple Files in Vim/Neovim Change Table Column Width in LaTeX Image or Table Side by Side in LaTeX LaTeX 并排显示图像或表格 Firenvim: Neovim inside Your Browser Content inside HTML tags missing in Latest Hugo? Creating Markdown Front Matter with Ultisnips Labelme JSON 标注格式转 voc XML 格式 Nifty Nvim Techniques That Make My Life Easier -- Series 6 macOS 下如何为视频制作字幕 Running Command Asynchronously inside Neovim Resolving Merge Conflict after Git Stash Pop Pylint: command not found? A Hands-on Experience with Neovim's Built-in LSP Support How to Convert PDF to Images with Imagemagick 互联网上常用缩略语集锦 File Backup in Neovim Converting PDF Pages to Images with Poppler Nifty Nvim Techniques That Make My Life Easier -- Series 5 Neovim Configuration for System-wide Use How to sort a list of tuple or list in Python -- lambda or itemgetter? Building A Vim Statusline from Scratch 人类第一颗原子弹爆炸始末 Distributed Training in PyTorch with Horovod Learning Expect Programming Essential Knowledge about SSH Nifty LaTeX Techniques -- Series 1 更改 Adsense 邮寄地址,重新寄送 PIN
What Is the Correct Way of Loop Through C++ Vector Using ...
2017-10-07 · via jdhao's digital space

It might seem naive to ask how to loop through a C++ vector using index. However, it is not: even experienced programmer may write buggy code to loop through a vector.

I have long been familiar with code snippet below:

vector<int> arr(100, 0);
for (int i = 0; i != arr.size(); ++i){
    // do something with arr[i]
}

Each time I write code like this, the compiler gives me warnings:

comparison between signed and unsigned integer expressions [-Wsign-compare]

The reason is simple: arr.size() has type vector<int>::size_type, which is unsigned. We are comparing signed types (int) with unsigned types (vector<int>::size_type), hence the warning. If you insist on using int as index for vector types, you are for some buggy code. The better way is to use unsigned type as index for vector, but we need to be careful.

Choosing the index type: size_t or size_type?#

Theoretically, we should declare the type of index i to be vector<int>::size_type. But it is a lot of code to type. So I prefer to use size_t as the type of index, which is also an unsigned type. Most of the time, you can safely use size_t as the index. If you are interested, you can check the difference between size_type and size_t here.

How to loop forward#

Looping forward through a vector using index is straightforward. See the sample code below:

vector<int> arr(100, 0);
for (size_t i = 0; i != arr.size(); ++i){
    // do something with arr[i]
}

How to loop backward#

The pitfall#

Looping backward through a vector when you declare the index as unsigned type has pitfalls that we should avoid. Unfortunately, I have fallen into this trap several times. Consider the following code:

for (size_t i = arr.size()-1; i >= 0; --i){
    // do something with arr[i]
}

This code has a serious bug: because i is unsigned type, so i will never be smaller than 0, as a result, the for loop never stops.

There are two ways to loop backward correctly, the first one is:

for (size_t i = arr.size()-1; i != (size_t)-1; --i){
    // do something with arr[i]
}

Because i is unsigned type, when i equals 0, i-1 will become (size_t)-1, which is the largest value that size_t can represent. Then the loop will stop correctly.

The second one is:

for (size_t i = arr.size(); i-- > 0; ){
    // do something with arr[i]
}

When i equals 0, the condition i-- > 0 will not be met, so the loop will terminate.

Ok, that is all I want to write in this post. Hope it can help you.

References#