如何解决退出状态1错误?

时间:2018-02-04 16:31:24

标签: c++ arrays function compiler-errors exitstatus

我想编写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

我无法找到我的错误,请帮助我。

1 个答案:

答案 0 :(得分: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;
}