C++ 返回整个数组
您可以使用数组元素的索引作为函数C++ 返回整个数组,c++,class,C++,Class,您可以使用数组元素的索引作为函数getcourt 比如说 How many courses are you currently taking? 2 What is your full name? Testing Name Type in 1 for Freshman, 2 for Sophomore, 3 for Junior or 4 for Senior. What year are you? 4 What is your current semester? Spring 2014 Plea
getcourt
比如说
How many courses are you currently taking? 2
What is your full name? Testing Name
Type in 1 for Freshman, 2 for Sophomore, 3 for Junior or 4 for Senior.
What year are you? 4
What is your current semester? Spring 2014
Please enter the name of all your courses.
Course #1 : C++
Course #2 : Adv C++
Here is your information:
Name : Testing Name
Semester : Spring 2014
Year : Senior
Course #1 : C++
Course #2 : C++
string getCohort( int i ) const;
函数必须返回与给定索引对应的元素,如果索引无效,则返回空字符串
另一种方法是使用标准类std::array
,并将其用作返回值。比如说
How many courses are you currently taking? 2
What is your full name? Testing Name
Type in 1 for Freshman, 2 for Sophomore, 3 for Junior or 4 for Senior.
What year are you? 4
What is your current semester? Spring 2014
Please enter the name of all your courses.
Course #1 : C++
Course #2 : Adv C++
Here is your information:
Name : Testing Name
Semester : Spring 2014
Year : Senior
Course #1 : C++
Course #2 : C++
string getCohort( int i ) const;
然后CName必须指向动态分配的数组,或者它应该是类型为std::vector
比如说
std::向量CName;
//
void setCourses(string courses[], int n);
或
#包括
//...
std::string*CName;
//...
void setCourses(const std::string courses[],int n)
{
CName=新标准::字符串[n];
std::副本(课程,课程+n,CName);
}
在最后一种情况下,不要忘记删除指针。这是大量代码。你应该单独开发新函数,如果你准备了一个新函数,你的问题会得到更多的关注。正如你的另一个问题已经提到的:使用
std::vector
而不是普通数组和原始指针!不能返回数组,只能返回数组的指针,这本身就不安全,而且容易出错!另外,我没有得到你的AmtClass
成员与你的关系,这背后的语义是什么??如果我应该使用向量,我会使用向量。AmtClass是收集有关我需要为数组创建空间的课程数量的信息strings@user3347541相信我,你应该为这个用例做好准备。其他任何东西都需要对代码进行更彻底的过度工作!在setcourse函数中,将数组更改为指针。@user3347541祝您好运。+1感谢您提到的std::array
!恐怕,USER 334 741对使用标准C++的所有建议都是很有抵抗力的:虽然……我只是做我所要求的。“我不知道CNNE是什么意思。”不,等等,没关系,他只是用非常奇怪的方式使用数组。
void setCourses(string courses[], int n);
void setCourses( const std::string courses[], int n )
{
CName.assign( courses, courses + n );
}
#include <algorithm>
//...
std::string *CName;
//...
void setCourses( const std::string courses[], int n )
{
CName = new std::string[n];
std::copy( courses, courses + n, CName );
}