gpt4 book ai didi

c++ - unordered_multimap 在 gnu++11 和 c++0x 中的不同行为

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:40:10 24 4
gpt4 key购买 nike

我在不同的编译器上编译了以下程序,并得到了不同的行为,

来源:

#include <iostream>
#include <sstream>
#include <unordered_map>

using namespace std ;

std::unordered_map<std::string,std::string> mymap;
std::unordered_multimap<std::string,std::string> mymultimap;
int main ()
{
DoAddItem() ;

std::cout << "mymap contains:";
for ( auto it = mymap.begin(); it != mymap.end(); ++it )
std::cout << " " << it->first << ":" << it->second;
std::cout << std::endl;

std::cout << "============================================" << std::endl ;
std::cout << "mymultimap contains:";
for ( auto it2 = mymultimap.begin(); it2 != mymultimap.end(); ++it2 )
std::cout << " " << it2->first << ":" << it2->second;
std::cout << std::endl;
return 0;
}

void DoAddItem()
{
std::pair<std::string,std::string> mypair[100];
int idx ;
std::string s1 ;
std::string s2 ;
for(idx=0;idx<10;idx++)
{
s1 = string("key") + int2str(idx) ;
s2 = string("val") + int2str(idx) ;
mypair[idx] = {s1,s2} ;
mymap.insert(mypair[idx]) ;
mymultimap.insert(mypair[idx]) ;
}//for
return ;
}

在 RedHat Linux 中用 g++ 4.4.6 编译如下:

g++  --std=c++0x unordered_map1.cpp -o unordered_map1.exe 

将得到 mymap 和 mymultimap 的正确答案,但在 MinGw 中: http://sourceforge.net/projects/mingwbuilds/?source=dlp

编译如下:

g++ -std=gnu++11 unordered_map1.cpp -o unordered_map1.exe

这一次,mymap 仍然得到正确答案,但是 mymultimap 都是空的,MinGw g++ 版本是

g++(rev1,由 MinGW-builds 项目构建)4.8.1

我对 c++11 很感兴趣,所以我在我的 winx 中下载了 MinGw 编译器,g++ 4.4.6,我的开发编译器,无法编译 c++11 进行测试。

我错过了什么?我的目标是测试 c++11,欢迎任何建议!!

编辑:

mymultimap.insert(mypair[idx]) ;   //won't work !!
mymultimap.insert(make_pair(s1,s2)) ; //This work !!

在我将代码更改为 make_pair 后,它可以在 MinGw 中运行并打印正确答案对于 mymultimap ....虽然这对我来说很奇怪 ~~

最佳答案

错误归档 http://gcc.gnu.org/bugzilla/show_bug.cgi?id=57619

这与mingw没有直接关系。用 g++4.8 编译的测试用例有同样的问题。但是在ideone上用g++4.7.2编译的同一个测试用例没有这个问题。这是 g++4.8 中的错误,您应该报告它(或者让我知道,我会为您报告)。

发生了什么:

调用 mymap.insert(mypair[0]); 将字符串移出 std::pair。因此,当调用 mymultimap.insert(mypair[0]); 时,字符串已被移动。

这是一个最小的测试用例:

std::unordered_map<std::string,std::string> mymap;
std::unordered_multimap<std::string,std::string> mymultimap;
int main ()
{
std::pair<std::string,std::string> mypair[1];
std::string s1 = std::string("key");
std::string s2 = std::string("val");
mypair[0] = {s1,s2};
mymap.insert(mypair[0]);
mymultimap.insert(mypair[0]);
std::cout << "mymultimap contains:";
for ( auto it2 = mymultimap.begin(); it2 != mymultimap.end(); ++it2 )
std::cout << " " << it2->first << ":" << it2->second;
}

关于c++ - unordered_multimap 在 gnu++11 和 c++0x 中的不同行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17039893/

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