【问题标题】:smallest element in a array of strings c++字符串数组中的最小元素c ++
【发布时间】:2014-11-28 22:06:10
【问题描述】:

我试图在字符串数组中找到最小的元素,但我不知道该怎么做。我想出了这个代码想法,它非常适用于 integers 但不适用于字符串。这将编译,尽管它只检查字符串中的第一个字符的 ASCII 值。换句话说,在字符串数组中:lists[5] = { "aaa", "z", "cccc", "tt", "jjj"};lists[1]"z" 是字符串的最小元素。但是,因为 'a' 是一个较低的 ASCII 值,所以代码将打印出 Smallest aaa 而不是 Smallest z。现在我知道我可以使用 .length 对字符串中的每个字符进行某种深切的同情,但我想使用一些简单的东西来解决这个问题,因为我想将它添加到一个将重载为整数的函数中,所以我可以在字符串和整数比较之间来回切换。但如果这不可能,我将只有两个单独的函数来处理每个函数。

如果您对如何找到字符串数组中的最小元素有什么建议?

#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main() {


string  lists[5] = { "aaa", "z", "cccc", "tt", "jjj"};
    string smallests;
    smallests = lists[0];
    for (int i = 0; i < 5; i++){
        cout << smallests << endl;
        if (lists[i] < smallests){   // Flip < to > to find largest
            smallests = lists[i];
        }
    }
    cout << "Smallest " << smallests << endl;
    cout << *min_element(lists, lists + 5) << endl;

return 0;
}

【问题讨论】:

  • 长度最小?还是按字母顺序?
  • 嗯,长度,但我现在可以看到字母顺序会起作用。如字符串列表[5] = { "a", "z", "c", "t", "j"};都将是相同的长度。但是一次做一件事,因为那个检查将是我现在拥有的代码哈哈。

标签: c++ arrays string algorithm


【解决方案1】:

最简单的做法是注意std::min_element 可以传递自定义比较函数。那么,让我们来定义什么是最小。

从 cmets 看来,您需要更短的字符串,然后按字典顺序对它们进行排序。

#include <string>
#include <algorithm>
#include <iostream>

bool smallest(std::string const & lhs, std::string const & rhs) {
    if (lhs.size() < rhs.size())
        return true;
    if (lhs.size() == rhs.size() && lhs < rhs)
        return true;
    return false;
}

int main() {
    std::string lists[5] = { "aaa", "z", "cccc", "tt", "jjj"};
    std::cout << *std::min_element(lists, lists + 5, smallest) << "\n";
}

哪些输出:

z

【讨论】:

    【解决方案2】:

    http://www.tutorialspoint.com/c_standard_library/string_h.htm

    你要比较的代码变成:

    if (strcmp(lists[i], smallests) < 0) {
        smallests = lists[i];
    }
    

    【讨论】:

    • 这是 C++。 operator&lt; 非常明确。
    • 这是 C++,字符串类 HAVE
    猜你喜欢
    • 2017-05-31
    • 2011-04-07
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-28
    • 1970-01-01
    • 2022-01-17
    相关资源
    最近更新 更多