简体   繁体   English

如何在字符串数组中查找元素个数(将字符串传递给函数)

[英]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: 由于这不是一种选择,请考虑一些替代方法:

  • Add another member function to Prerequisites to inform it how large the array will be when you do call orderClasses() . Prerequisites添加另一个成员函数,以通知您在调用orderClasses()时数组将有orderClasses()
  • Use a sentinel value for the last string in the array so that when you see that value in the function, you know you have reached the end. 对数组中的最后一个字符串使用哨兵值,这样当您在函数中看到该值时,便知道已到达末尾。
  • Make the first string in the array a string containing the number of elements in the array. 使数组中的第一个字符串成为包含数组中元素数量的字符串。

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.

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