make_pair:error C2665: no overloaded function could convert all the argument types

huangapple go评论151阅读模式
英文:

make_pair:error C2665: no overloaded function could convert all the argument types

问题

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

using namespace std;

int main()
{
    vector<pair<string, int>> v;
    string word;
    int i;  // Changed 'i' to 'int'
    while (cin >> word >> i)  // Changed 'i' to 'int'
        v.push_back(make_pair(word, i));

    return 0;
}

It reports:

error C2665: 'std::vector<std::pair<std::string, int>,std::allocator<std::pair<std::string, int>>>::push_back': no overloaded function could convert all the argument types

Can someone tell me where the problem is?

英文:

An exercise on C++ primer:Write a program to read a sequence of strings and ints,storing each into a pair.Store the pairs in a vector.

#include &lt;vector&gt;
#include &lt;utility&gt;
#include &lt;string&gt;
#include &lt;iostream&gt;

using namespace std;

int main()
{
	vector&lt;pair&lt;string, int&gt;&gt; v;
	string word, i;
	while (cin &gt;&gt; word &gt;&gt; i)
		v.push_back(make_pair( word, i ));
	
	return 0;
}

It reports:

> error C2665:
> 'std::vector<std::pair<std::string,int>,std::allocator<std::pair<std::string,int>>>::push_back':
> no overloaded function could convert all the argument types

Can someone tell me where the problem is?

答案1

得分: 4

You define the variable i as a std::string, when you're supposed to define it as an int:

std::string word;
int i;

With the current code, the call

make_pair( word, i )

is the same as

make_pair<std::string, std::string>( word, i )

There's no automatic conversion anywhere from std::pair<std::string, std::string> (created by your make_pair call) to a std::pair<std::string, int>. The two types are just not the same and not compatible in any way.

英文:
string word, i;

You define the variable i as a std::string, when you're supposed to define it as an int:

std::string word;
int i;

With the current code, the call

make_pair( word, i )

is the same as

make_pair&lt;std::string, std::string&gt;( word, i )

There's no automatic conversion anywhere from std::pair&lt;std::string, std::string&gt; (create by your make_pair call) to a std::pair&lt;std::string, int&gt;. The two types are just not the same and not compatible in any way.

huangapple
  • 本文由 发表于 2023年3月8日 16:50:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/75670982.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定