-3

我想编写 c++ 代码,它将所有与输入值长度相同的元素分开

#include <iostream>
#include <vector>
using namespace std;
string database[] = {"green", "stupid", "boy", "girl", "forest", "mobile", "morning", "love", "keyboard", "incredible"};
string input;
string count(string input, string database[]){
    string lengthFilter[] = {};
    int inputLength = input.length();
    for (int i = 0; i < database->length(); ++i){
        if (database[i].length() == inputLength)
        {
            lengthFilter[lengthFilter->length()] = database[i];

        }
    }
    return (lengthFilter);
}

int main()
{
    cin >> input;
    cout << count(input, database);
    return 0;
}

但它给出了错误

main.cpp: In function 'std::__cxx11::string count(std::__cxx11::string, std::__cxx11::string*)':
main.cpp:16:22: error: could not convert 'lengthFilter' from 'std::__cxx11::string [0] {aka std::__cxx11::basic_string<char> [0]}' to 'std::__cxx11::string {aka std::__cxx11::basic_string<char>}'
  return (lengthFilter);
                      ^

exit status 1

我找不到我的错误,请帮助我。

4

1 回答 1

2

您深入探讨了内置 C++ 数组和[]语法的缺点。这个:

[]

并不总是意味着你认为的意思。其含义因上下文而异。在声明中:

string database[] = // ...

这意味着您正在声明一个内置数组。但是,在函数参数中:

string count(string input, string database[])

这是一个指针。上面的行等价于:

string count(string input, string* database)

另请注意:

string lengthFilter[] = {};

声明一个大小为零的内置数组。我认为这不是您想要的,因为内置数组是固定大小的。他们不调整大小。

所以你应该在这里做的是使用std::vector

#include <iostream>
#include <vector>

using namespace std;

vector<string> database = {
    "green", "stupid", "boy", "girl", "forest", "mobile", "morning", "love",
     "keyboard", "incredible"
};

string input;

vector<string> count(string input, const vector<string>& database)
{
    vector<string> lengthFilter;
    auto inputLength = input.length();
    for (const auto& i : database) {
        if (i.length() == inputLength) {
            lengthFilter.push_back(i);
        }
    }
    return lengthFilter;
}

int main()
{
    cin >> input;
    for (const auto& i : count(input, database)) {
        cout << i << '\n';
    }
    return 0;
}
于 2018-02-04T16:50:05.580 回答