C++ VS17 给出与 Linux 子系统中相同代码不同的输出

C++ VS17 gives different output than same code in Linux Subsystem

我找不到这个问题的答案。我希望它不是重复的。我为 leetcode.com 挑战编写了代码,它在 VS17 中按预期工作,但在 leetcode 或我用 g++ 编译的 Ubuntu WSL 上没有。该代码搜索具有唯一字母的最长子字符串。字符串 "pwwkew" 的答案是 3(VS17 得到 3),但在 Linux 和 leetcode 上吐出 4。我猜这与 MinGW vs G++ 有关。在 Ubuntu 我用几个不同版本的 C++ 编译了程序,使用:g++ -Wall -Wextra -Werror string.cpp -std=c++1y -o string

提前致谢!这也是我的第一个 post 所以对我放轻松 :)。

#include <algorithm>
#include <vector>
#include <iostream>
#include <string>
#include <set>
#include <unordered_set>
using namespace std;


/*
Input: "abcabcbb"
Output: 3
Explanation: The answer is "abc", with the length of 3.
*/

int main()
{
    string s = "pwwkew";

    //this algorithm adds unique chars to a set in the order that they appear in the string
    //after each for loop, the maximum number between maxLen and the size of the set is recorded
    //when a duplicate letter is found, all of the letters up until and including the last
    //occurence of that letter are erased, so the remaining letters are only the uniques in the current 'substring'
    unordered_set<char> seen;
    int maxLen = 0;
    for (int end = 0; end < s.size(); end++)
    {       
        if (seen.insert(s[end]).second == false)
        {
            if (seen.begin() == seen.find(s[end]))
            {
                seen.erase(seen.begin());
            }
            else {
                seen.erase(seen.begin(), seen.find(s[end+1]));
            }
            seen.insert(s[end]);
        }
        maxLen = max(maxLen, (int)seen.size());
    }


    return 0;
}    

编辑:我添加了一个迭代器循环以在每次初始 for 循环执行后打印集合中的值,VS17 打印:

p
p w
w
w k
w k e
k e w

虽然 Linux 打印:

p
w p
w p
k p w
e k p w
w

所以我猜插入顺序被一个编译器颠倒了,这会导致我的 set.erase 以错误的顺序执行?

unordered_set 以不确定的顺序存储其元素。尝试删除您使用 seen.erase 添加到集合中的前 2 个元素,两个迭代器将不起作用。

重新考虑您正在做的事情并选择一个不同的容器。

您似乎假设了 unordered_set 中值的排序。请记住,顺序可能取决于实现,不同的实现可能会有不同的行为。