[英]How to find the no of elements in an string array (the string is passed to a function)
#include<iostream>
#include<string>
using namespace std;
class Prerequisites
{
public:
void orderClasses(string* Input);
};
void Prerequisites::orderClasses(string* Input)
{
// Need to find the length of the array Input
}
int main()
{
Prerequisites A;
string classes[]={"CSE121: CSE110",
"CSE110:",
"MATH122:"
};
A.orderClasses(classes);
}
I need to find the length of the array classes[] in the methos orderClasses. 我需要在方法orderClasses中找到数组classes []的长度。 I cannot alter the signature of the method orderClasses !
我无法更改方法orderClasses的签名! That is a requirement.
这是一个要求。
You should pass the number of elements in the array to orderClasses()
. 您应该将数组中的元素数量传递给
orderClasses()
。 Since that is not an option, consider some alternatives: 由于这不是一种选择,请考虑一些替代方法:
Prerequisites
to inform it how large the array will be when you do call orderClasses()
. Prerequisites
添加另一个成员函数,以通知您在调用orderClasses()
时数组将有orderClasses()
。 None of these are good solutions to the problem: the best option while still using an array, of course, is just to pass the array size to the function. 这些都不是解决问题的好方法:当然,仍然在使用数组时最好的选择就是将数组的大小传递给函数。 In most scenarios, it would be even better not to use an array at all and just pass a
std::vector<std::string>
containing the strings. 在大多数情况下,最好完全不使用数组,而只传递包含字符串的
std::vector<std::string>
。
The information is just not there. 信息不存在。 Can't you add a last item to the
classes[]
array that's a "well-known end-marker/sentinel"? 不能将最后一个项目添加到
classes[]
数组中是“众所周知的结束标记/前哨”吗? That meets the requirement of not changing the method signature (you're just changing the data passed to it, not the signature;-). 这符合不更改方法签名的要求(您只需更改传递给它的数据,而不是签名;-)。
我从未听说过,在c ++中,人们使用数组时会使用功能更强大的STL工具。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.