小编Alb*_*ieu的帖子

c++ 中的 [] 操作后 unordered_map 元素消失

在下面的 C++ 代码中,unordered_map 元素意外消失的行为让我很困惑。在第一个for循环中,我将每个元素的剩余部分存储在timemoduled by 60 中,并将其计数存储在 中unordered_map<int, int> m,在第二个 for循环中,我将内容打印在 中m,到目前为止,一切似乎都正常。 cout如下

0:1
39:1
23:1
18:1
44:1
59:1
12:1
38:1
56:2
17:1
37:1
24:1
58:1
Run Code Online (Sandbox Code Playgroud)

然而在第三个for循环中,它只打印了 中的部分元素m

0:1
39:1
58:1
0:1
Run Code Online (Sandbox Code Playgroud)

看来很多元素都mn += m[remainder]*m[60-remainder];操作删除了。我对这种行为感到很困惑,你能理解这是怎么回事吗?实在是太迷茫了。

#include <iostream>
#include<unordered_map>
#include<vector>
using namespace std;
int main() {
    vector<int> time ({418,204,77,278,239,457,284,263,372,279,476,416,360,18});
    int n =0;
    unordered_map<int,int> m; // <remiander,cnt>
    for (auto t:time)
        m[t%60]++;
    for (auto [remainder,cnt]:m) …
Run Code Online (Sandbox Code Playgroud)

c++

1
推荐指数
1
解决办法
198
查看次数

type 将 char 转换为 string

我只是好奇相同的类型转换格式适用于 char、int 以及其他许多类型,但为什么它不适用于字符串,即(string) 'c'屏幕后面出了什么问题?

#include <iostream>
using namespace std;

int main(){
    char a = 'a';
    cout << (char) 99 <<endl;
    cout << (int) 'c'<<endl;
    cout<< (string) 'c' + "++" <<endl;  // why this does not work??? 
    cout<< string (1, 'c') + "++" <<endl;
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

c++ string char casing implicit-conversion

-1
推荐指数
1
解决办法
256
查看次数

标签 统计

c++ ×2

casing ×1

char ×1

implicit-conversion ×1

string ×1