gpt4 book ai didi

c++ - C++ 中的排序字符串不能正确比较?

转载 作者:行者123 更新时间:2023-11-28 07:04:41 24 4
gpt4 key购买 nike

基本上,我有两个列表。列表A有条款,并列出B有被打乱的术语。我正在尝试解读 B通过复制 A ,对其中的每个字符串进行排序,然后对B中的字符串进行排序并将它们与 A 的排序版本匹配.然后我可以从排序的 A 中获取索引并通过在 A 中放置相同的索引来找到原件.

到目前为止,我的代码看起来不错,但字符串永远不会彼此相等。我已经尝试了我所知道的每一种比较形式,现在我正在做 str1.compare(str2) == 0 .

我的代码:
我有vector<string> linesvector<string> keywords .然后我有 vector<string> sorted_kws这是 keywords一切都安排好了。

// Finding matching strings
for (int i = 0; i < lines.size(); i++) {
for (int j = 0; j < sorted_kws.size(); j++) {
if (lines[i].compare(sorted_kws[j]) == 0)
cout << keywords[j] << ",";
}
}
cout << endl;

我做错了什么?
我也尝试使用 std::find但这也不起作用。
另外,我打印了所有内容以确保它看起来正确。字符串完全相同,应该绝对相等,但事实并非如此。

最佳答案

如果不查看更多代码,就很难(即不可能)准确猜出您的问题出在哪里。也就是说,让基本想法发挥作用当然是可能的。

我想我会通过定义一个存储字符串的原始形式和排序形式的类来实现。当您进行比较时,它会根据排序后的形式进行比较,但是当您将其写入流时,它会显示原始字符串:

class sorted_string {
std::string sorted;
std::string original;
public:
sorted_string(char const *input) :sorted(input), original(input) {
std::sort(sorted.begin(), sorted.end());
}

friend std::ostream &operator<<(std::ostream &os, sorted_string const &s) {
return os << s.original;
}

bool operator<(sorted_string const &other) const {
return sorted < other.sorted;
}
};

使用它,其余代码变得非常简单:

int main() {
// create two sets of input strings:
std::set<sorted_string> in1{ "xzy", "bac", "dffed", "iii", "iji" };
std::set<sorted_string> in2{ "yxz", "cab", "yyy", "ffedd", "iop" };

// print out the intersection based on sorted comparison:
std::set_intersection(
in1.begin(), in1.end(),
in2.begin(), in2.end(),
std::ostream_iterator<sorted_string>(std::cout, "\n"));
}

我想您可以使用 std::map<std::string, std::string> 来做同样的事情通过使用字符串的排序版本作为键,并将原始版本作为映射值,但至少在副手看来,这可能会导致更多工作而不是更少。

关于c++ - C++ 中的排序字符串不能正确比较?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21945034/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com