The super for loop in C ++ practice and the difference between list and java, listjava
You can directly modify the attributes of an object in the For loop in Java.
import java.util.ArrayList;import java.util.List;import java.util.regex.*;public class main { static class Student { String name; int id; public Student(String name, int id) { this.name = name; this.id = id; } public void setName(String name) { this.name = name; } @Override public String toString() { return "Student [name=" + name + ", id=" + id + "]"; } } public static void main(String[] args) { List
mStudents = new ArrayList
(); mStudents.add(new Student("Tony", 1)); mStudents.add(new Student("Lili", 2)); System.out.println("BEFORE: " + mStudents); for (Student student : mStudents) { if (student.id == 1) { student.setName("zhangsan"); } } System.out.println("AFTER: " + mStudents); }}
Running result:
BEFORE: [Student [name=Tony, id=1], Student [name=Lili, id=2]]AFTER: [Student [name=zhangsan, id=1], Student [name=Lili, id=2]]
Direct modification in C ++ does not change the object attribute in the List. The result is as follows:
for (Student student : mStudents) { if (student.id == 1) { student.setName("zhangsan"); } }
To achieve the effect of java, you need to add an address character:
for (Student &student : mStudents) { if (student.id == 1) { student.setName("zhangsan"); } }
Because C ++ focuses on value transfer and address transfer. This distinction is not made in java, but it is a transfer address. Therefore, the sub-function can directly modify the attribute values of the passed objects. In C ++, you need to add the & get address character to convert it into a transfer address.