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

推荐订阅源

Y
Y Combinator Blog
B
Blog
S
SegmentFault 最新的问题
Vercel News
Vercel News
博客园 - 聂微东
宝玉的分享
宝玉的分享
C
Check Point Blog
有赞技术团队
有赞技术团队
IT之家
IT之家
V
V2EX
爱范儿
爱范儿
GbyAI
GbyAI
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Microsoft Azure Blog
Microsoft Azure Blog
P
Proofpoint News Feed
博客园 - 司徒正美
博客园_首页
Last Week in AI
Last Week in AI
博客园 - 叶小钗
量子位
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
F
Fortinet All Blogs
腾讯CDC
J
Java Code Geeks

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#