ページ 11

std::vector,std::pairについて

Posted: 2018年1月21日(日) 23:05
by 初心.者
C++初心者です。emplace_backについて知りたかったので、このような簡単なコードを書いたのですがエラーになってしまいます。
どのように解決したらよいかをご教示いただけないでしょうか。よろしくお願いいたします。

コード:

#include <Windows.h>

typedef struct t
{
	int n;

	t(){}
	t(int&){}
	t(int&&) {}

	t& operator=(t&)
	{
		OutputDebugStringA("copy\r\n");

		return *this;
	}

	t& operator=(t&&)
	{
		OutputDebugStringW(L"move\r\n");

		return *this;
	}
}tt;

#include <iostream>
#include <vector>
#include <utility>
#include <string>
#include <algorithm>

int main()
{
	std::vector<std::pair<int, tt>> v;

	v.emplace_back(3, tt(1));

	return 0;
}
<!--ビルド出力-->
1>test.cpp
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.12.25827\include\xmemory0(945): error C2660: 'std::pair<int,tt>::pair': 関数に 2 個の引数を指定できません。
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.12.25827\include\vector(936): note: コンパイル対象の関数 テンプレート インスタンス化 'void std::_Default_allocator_traits<_Alloc>::construct<_Ty,int,t>(_Alloc &,_Objty *const ,int &&,t &&)' のリファレンスを確認してください
1> with
1> [
1> _Alloc=std::allocator<std::pair<int,tt>>,
1> _Ty=std::pair<int,tt>,
1> _Objty=std::pair<int,tt>
1> ]
1>c:\program files (x86)\microsoft visual studio\2017\community\vc\tools\msvc\14.12.25827\include\vector(957): note: コンパイル対象の関数 テンプレート インスタンス化 'void std::_Default_allocator_traits<_Alloc>::construct<_Ty,int,t>(_Alloc &,_Objty *const ,int &&,t &&)' のリファレンスを確認してください
1> with
1> [
1> _Alloc=std::allocator<std::pair<int,tt>>,
1> _Ty=std::pair<int,tt>,
1> _Objty=std::pair<int,tt>
1> ]
1>c:\users\\\test.cpp(36): note: コンパイル対象の関数 テンプレート インスタンス化 'void std::vector<std::pair<int,tt>,std::allocator<_Ty>>::emplace_back<int,tt>(int &&,tt &&)' のリファレンスを確認してください
1> with
1> [
1> _Ty=std::pair<int,tt>
1> ]
1>プロジェクト "aaa.vcxproj" のビルドが終了しました -- 失敗。
========== ビルド: 0 正常終了、1 失敗、0 更新不要、0 スキップ ==========

Re: std::vector,std::pairについて

Posted: 2018年1月21日(日) 23:16
by purin52002
こんにちは
pair型を作るにはstd::make_pairを使います。
36行目を
v.emplace_back(std::make_pair(3, tt(1)));
とすればうまくいくはず、、、。

Re: std::vector,std::pairについて

Posted: 2018年1月22日(月) 11:01
by かずま
コピーコンストラクタがないからでしょう。

t(const t&){} を追加してみてください。

Re: std::vector,std::pairについて

Posted: 2018年1月22日(月) 11:03
by かずま
ムーブコンストラクタを追加してもいいようです。

t(t&&){} を追加してみてください。

Re: std::vector,std::pairについて

Posted: 2018年1月22日(月) 15:42
by 初心.者
ありがとうございます。moveおよびcopyコンストラクタを追加したところうまくいきました。解決とさせていただきます。