Iterate through a C++ Vector using a #39;for#39; loop(使用“for循环遍历 C++ 向量)
问题描述
我是 C++ 语言的新手.我已经开始使用向量,并注意到在我看到的所有通过索引迭代向量的代码中,for 循环的第一个参数总是基于向量的东西.在 Java 中,我可能会用 ArrayList 做这样的事情:
I am new to the C++ language. I have been starting to use vectors, and have noticed that in all of the code I see to iterate though a vector via indices, the first parameter of the for loop is always something based on the vector. In Java I might do something like this with an ArrayList:
for(int i=0; i < vector.size(); i++){
   vector[i].doSomething();
}
有什么原因我在 C++ 中看不到这个吗?这是不好的做法吗?
Is there a reason I don't see this in C++? Is it bad practice?
推荐答案
有什么原因我在 C++ 中看不到这个吗?这是不好的做法吗?
没有.这不是一个坏习惯,但以下方法使您的代码具有一定的灵活性.
No. It is not a bad practice, but the following approach renders your code certain flexibility.
通常,在 C++11 之前,迭代容器元素的代码使用迭代器,例如:
Usually, pre-C++11 the code for iterating over container elements uses iterators, something like:
std::vector<int>::iterator it = vector.begin();
这是因为它使代码更加灵活.
This is because it makes the code more flexible.
所有标准库容器都支持并提供迭代器.如果在以后的开发中需要切换到另一个容器,则不需要更改此代码.
All standard library containers support and provide iterators. If at a later point of development you need to switch to another container, then this code does not need to be changed.
注意:编写适用于所有可能的标准库容器的代码并不像看起来那么容易.
Note: Writing code which works with every possible standard library container is not as easy as it might seem to be.
这篇关于使用“for"循环遍历 C++ 向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:使用“for"循环遍历 C++ 向量
				
        
 
            
        基础教程推荐
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
 - 在 C++ 中计算滚动/移动平均值 2021-01-01
 - 如何在 C++ 中初始化静态常量成员? 2022-01-01
 - 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
 - 常量变量在标题中不起作用 2021-01-01
 - C++结构和函数声明。为什么它不能编译? 2022-11-07
 - 如何检查GTK+3.0中的小部件类型? 2022-11-30
 - 这个宏可以转换成函数吗? 2022-01-01
 - 我有静态或动态 boost 库吗? 2021-01-01
 - 如何通过C程序打开命令提示符Cmd 2022-12-09
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				