我有一个程序,我使用向量为结构创建n个对象。我想将这个向量传递给函数get_stud_data,我输入了学生的名字。我想要并将所有矢量对象返回到主函数
#include <iostream>
#include <string>
#include <vector>
#include "stdio.h"
using namespace std;
struct students
{
string name; // I am not sure
int roll_no;
};
vector<p>& get_stud_data(vector<students> & p, int n)
{
for(int i=0;i<n;i++)
{
cout<<"Enter Name of " <<i+1<<"th student\n";
cin>> p[i].name;
}
return p;
}
int main()
{
int n;
cout<<" Enter the number of students: ";
cin>> n;
vector<students> p(n); // creating n objects for struct students
// Want to retrieve the objects here.
p=get_stud_data()
return 0;
}
答案 0 :(得分:0)
你不需要。您将向量作为引用传递,以便您的函数可以更改它:
return this.connectivityService.isOnline()
.flatMap((isOnline: boolean) => {
if (isOnline) {
return Observable.of(); // subscribe() is not called
} else {
return Observable.throw(new OfflineError('The device is offline.'));
}
})
.do(() => console.log('Do things here'));
如果你真的想要返回一个矢量,你可以。在这个练习中,这是毫无意义的,因为那时你有两个:
#include <iostream>
#include <string>
#include <vector>
using namespace std;
struct student
{
string name;
int roll_no;
};
void get_student_data(vector<student>& students)
{
for(int i = 0; i < students.size() ; i++ )
{
cout << "Enter Name of " << i+1 << "th student\n";
cin >> students[i].name;
}
}
int main()
{
int n;
cout << " Enter the number of students: ";
cin >> n;
vector<student> students(n);
get_student_data(students);
// cout some students here to see it worked
return 0;
}
答案 1 :(得分:0)
如果您真正想要的是阅读n个学生的矢量并将其返回给来电者,您可以这样做:
{
"private": true,
"scripts": {
"prod": "gulp --production",
"dev": "gulp watch"
},
"devDependencies": {
"bootstrap-sass": "^3.3.7",
"gulp": "^3.9.1",
"jquery": "^3.1.0",
"laravel-elixir": "^6.0.0-11",
"laravel-elixir-vue-2": "^0.2.0",
"laravel-elixir-webpack-advanced": "*",
"laravel-elixir-webpack-official": "*",
"lodash": "^4.14.0",
"multiselect": "^0.9.12",
"node-sass": "^3.10.0",
"notifyjs-browser": "^0.4.2",
"sweetalert": "^1.1.3",
"vue": "^2.1.0",
"vue-resource": "^1.0.2",
"vue-router": "^0.7.13",
"vuetable-2": "^1.2.0",
"vuex": "^2.1.1",
"whatwg-fetch": "^1.0.0",
"wow.js": "^1.2.2"
},
"dependencies": {
"laravel-echo": "^1.0.5",
"pace": "0.0.4",
"pace-js": "^1.0.2",
"pusher-js": "^3.2.1"
}
}
此外,我在您的代码中注意到您创建了给定大小为n的向量,并将其传递给函数以读取其内容。因此,如果您真的想要创建给定大小的向量,并让该函数只读取该向量中的学生数据,您只需将vector<student> get_student_data(int n)
{
vector<student> v(n);
for (int i = 0; i < n; i++)
{
cout << "Enter Name of " << (i+1) <<"th student\n";
cin >> v[i].name;
}
return v;
}
作为输入/输出参数传递(使用reference:{{ 1}}),没有指定额外的vector<student>
参数,因为向量知道自己的大小(例如,您可以使用vector<student>&
查询):
int n