简体   繁体   中英

C++ vector input through a loop

I am trying to add multiple strings into a vector through a for loop, I can do this easily with an array but I am having trouble doing the same on a vector. Below is an example of the array I would like to try to convert into a vector.

Array Style

String StudentNames[];
int StudentNumbers;
for(int i = 0; StudentNumbers > i; i++){
cin >> StudentNames[i];
}

Vector Style

vector<string> StudentNames;
int StudentNumbers;
//How do i add a for loop using vector and add strings to it similar to the array above?

Use std::vector::push_back and std::getline as :-

std::string sn; //temporary string

for(int i = 0; StudentNumbers > i; i++){
std::getline(std::cin, sn); 

StudentNames.push_back(sn); 
}

And then you can access ith name as StudentNames[i]

One way is to create the vector with the right size for the loop:

int StudentNumbers = ....;
std::vector<std::string> studentNames(StudentNumbers);
for(auto it = studentNames.begin(), end = studentNames.end(); it != end; ++it){
  std::cin >> *it;
}

or

int StudentNumbers = ....;
std::vector<std::string> studentNames(StudentNumbers);
for(auto& s = 0; studentNames){
  std::cin >> s;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM