[英]how to loop over vector size C++
我是C ++編程的新手,並且有一個關於Vector大小和for循環的問題。
假設我的Vector大小為3,其中包含值:
x = [Susan 13, Female, Chicago Illinois] //this will be the comparison point
y = [Sally 18, Female, Tokyo Japan]
z = [Rowland 2, Male, Arizona California] //y & z will be compared to x
+...other vectors depending on how many the user inputs
我想創建一個for循環,通過將y&z與x進行比較來生成每個年齡。 所以我希望它像
x[0] - y[0] --> 5 //difference of the ages
x[0] - z[0] --> 11
到目前為止,我有這個:
vector<string> age, gender, location;
void ageDiff(vector<string> a, vector<string> g, vector<string> l){
//i want to start calculating the age differences but i'm not sure how to loop depending on how many data the user inputs
}
int main(){
int n;
std::cout << "How many data will you input? ";
std::cin >> n;
for (a=0;a<n;a++){
std::cout << "Please enter the data for person #" << a;
std::cin >> a;
std::cin >> b;
std::cin >> c;
age.push_back(a);
gender.push_back(b);
location.push_back(c);
for (a=0;a<(age.size()-1);a++){
ageDiff(age, gender, location)
}
您的示例不是如何使用C ++。 創建一個包含int年齡,布爾或枚舉性別以及字符串位置作為私有成員的類/結構。 這些成員應該可以通過int getAge()
和void setAge(int newAge)
類的方法進行訪問。 這將大大簡化您的原始任務。 創建人的矢量people
和循環遍歷它:
for (size_type i = 0; i < people.size(); i++)
for (size_type j = i + 1; j < people.size(); j++)
std::cout << "age difference between " << i << " and " << j << " is "
<< std::abs(people[i].getAge() - people[j].getAge()) << "." << std::endl;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.