Hello, @course2520194271, and welcome to the forums.
The code you supplied declares a vector of type char
. The next line would be the first line of a for
loop used to iterate through the elements of the vector. The variable i
is used as the index, so we can tell the computer which element of the vector to look at. For example, if I had the following vector:
std::vector<char> name;
name.push_back('h');
name.push_back('e');
name.push_back('r');
name.push_back('c');
name.push_back('u');
name.push_back('l');
name.push_back('e');
name.push_back('s');
//I've added each letter (ie. char) as an element in the vector called name.
//The elements are separated by commas.
// The vector now could be visualized like this:
// { 'h', 'e', 'r', 'c', 'u', 'l', 'e', 's' }
//'h' is at index 0, 'e' is at index 1, 'r' is at index 2, and so on:
//{ 'h', 'e', 'r', 'c', 'u', 'l', 'e', 's' }
// 0 1 2 3 4 5 6 7 <--Index values
//To access the letter 'r' I would use: name[2];
So, you are starting with i = 0;
because the first element of the vector is at index 0. The next part of the for
loop is i < incorrect.size();
. .size()
is a method that returns the size of the vector. A vector’s size is the number of elements it contains. In my example above, the vector, name
has a size of 8. There are 8 elements that we can access using the index values (0-7). That is why we use
i < incorrect.size()
. The loop will continue iterating until this condition is no longer true, so when i
gets to 8, 8 is not less than 7, so the loop is finished. Therefore, i
will start at 0
, and be incremented by 1 following each iteration of the loop until it gets to 8. That will give us the index values we need to access every element in the vector: (0, 1, 2, 3, 4, 5, 6, 7). We could use that to print the name in the console from my previous example:
#include <iostream>;
#include <vector>;
int main() {
std::vector<char> name;
name.push_back('h');
name.push_back('e');
name.push_back('r');
name.push_back('c');
name.push_back('u');
name.push_back('l');
name.push_back('e');
name.push_back('s');
for(int i = 0; i < name.size(); i++) {
std::cout << name[i];
}
return 0;
}
Output:
hercules
First name[0]
was printed, so ‘h’.
Then name[1]
, so ‘e’, and so on until i
was incremented to 8
at which point the for
loop was exited.
As far as how the code you supplied:
It doesn’t. Not by itself. It could be used to iterate over the elements in the vector called incorrect
, then additional code could be written to make the necessary comparisons, and determine a result. I did a search, and found this video. I didn’t watch the whole thing, but perhaps it will help.
Note: We could also simply assign elements to the name
vector at the time is was declared instead of repeatedly using push_back()
:
std::vector<char> name = { 'h', 'e', 'r', 'c', 'u', 'l', 'e', 's' };