如果我尝试将函数声明为void some_function(vector<pair<int, int> > theVector)
,我会收到一个错误(大概是在“pair<int
”之后的逗号中。有关如何将这个向量与对传递到函数中的任何想法?
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <vector>
void someFunc(int x, int y, vector<pair<int, int> > hello);
int main()
{
int x = 0;
int y = 5;
vector<pair<int, int> > helloWorld;
helloWorld.push_back(make_pair(1,2));
someFunc(x,y,helloWorld);
}
void someFunc(int x, int y, vector<pair<int, int> > hello)
{
cout << "I made it." << endl;
}
错误:尚未声明'vector'
你需要为vector,pair,make_par提供完整的命名空间,它们来自std命名空间:
void someFunc(int x, int y, std::vector<std::pair<int, int> > hello);
int main()
{
int x = 0;
int y = 5;
std::vector<std::pair<int, int> > helloWorld;
helloWorld.push_back(std::make_pair(1,2));
someFunc(x,y,helloWorld);
return 0;
}
void someFunc(int x, int y, std::vector<std::pair<int, int> > hello)
{
std::cout << "I made it." << std::endl;
}
旁注:您可以通过引用将向量传递给someFunc,这将省略不必要的副本:
void someFunc(int x, int y, const std::vector<std::pair<int, int> >& hello);
^^^ ^^
你没有包括定义<utility>
的std::pair
,你使用的是vector
和pair
,而不是std::vector
和std::pair
。
所有标准模板库都在命名空间std
中,因此您必须使用std
(例如std::vector
)为STL中的类型添加前缀。另一种方法是在包含using std::vector;
后添加<vector>
。
你有没有包括<vector>
和<utility>
?您应该在std::
和vector
上使用pair
命名空间。
例如。 void some_function(std::vector< std::pair<int, int> > theVector)
编辑:当然,您通常不应该按值传递向量,而是通过引用传递。
例如。 void some_function(std::vector< std::pair<int, int> >& theVector)
我嘲笑你的代码,你只需要在你的std
下方添加#include
命名空间。并且您不需要添加#include <utility>
它可以在没有它的情况下工作。
using namespace std