除了迭代器对象之外,遍历向量的不同方法有哪些?

huangapple go评论67阅读模式
英文:

What are different ways to iterate through a vector, other than the iterator object?

问题

这里的函数接受一个包含个位数元素的向量,将向量转换为一个整数,将该数加一,然后再将加一后的数重新转换为一个向量并返回。

函数代码如下:

public static Vector<Integer> plusOne(Vector<Integer> digits) {
    int dig = 0;
    Iterator it = digits.iterator();
    Vector<Integer> res = new Vector<Integer>();
    while (it.hasNext()) {
        dig = (dig * 10) + ((int) it.next());
    }
    dig = dig + 1;
    while (dig != 0) {
        int temp = dig % 10;
        res.add(temp);
        dig = dig / 10;
    }
    return res;
}

我的问题: 除了使用迭代器对象之外,是否有其他遍历向量的替代方法?

英文:

This function here takes a vector of single digit elements, converts the vector into a whole number, increments that number, and then reconverts that incremented number into a vector and returns it.

Here the function :

public static Vector&lt;Integer&gt; plusOne(Vector&lt;Integer&gt; digits) {
		int dig=0;
		Iterator it=digits.iterator();
		Vector&lt;Integer&gt;res=new Vector&lt;Integer&gt;();
		while(it.hasNext()) {
			dig=(dig*10)+((int)it.next());
		}
		dig=dig+1;
		//System.out.println(dig);
		while(dig!=0)
		{
			int temp=dig%10;
			res.add(temp);
			dig=dig/10;
		}
		return res;
	}

My question : Are there any alternate ways to traverse through the vector instead of using the iterator object

答案1

得分: 0

以下是翻译好的部分:

你可以使用增强型for循环遍历一个向量。

 for (Integer digit : digits) {   

 }

我们还知道向量的大小,我们可以使用 vector.size() 来编写一个for循环。

 for(int index = 0; index < digits.size(); index++) {      
   System.out.println(digits.get(index));
 }

你还可以按照这里提供的其他方法进行操作(链接:http://javainsimpleway.com/vector-with-looping/)。

英文:

You can use Enhanced for loop to iterate over a vector

 for (Integer digit : digits) {   

 }

We also know the size of the vector, we can write a for loop using vector.size().

 for(int index = 0; index &lt; digits.size(); index++) {      
   System.out.println(digits.get(index));
 }

You can also follow the other ways given here

huangapple
  • 本文由 发表于 2020年10月14日 19:36:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/64352397.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定