如何在c++中传递vector作为实参

  • 本文关键字:vector 实参 c++ c++
  • 更新时间 :
  • 英文 :


我需要创建一个c++程序来实现sum= num1 + num2, sum= num1 - num2, sum= num1 * num2,其中sum,num1,num2是包含存储整数的vector的对象。我需要使用操作符重载。这是我想出的代码,但我不能理解这些错误的原因。我将vector声明为'std::vector n;',并尝试将另一个vector作为参数传递给函数。我对堆栈溢出和c++编程都是新手。

#include<iostream>
using namespace std;

class NUM
{
private:
std::vector<int> n ;

public:
//function to get number
void getNum(std::vector<int> x)
{
n=x;
}
//function to display number
void dispNum(void)
{
cout << "Number is: " << n;
}
//add two objects - Binary Plus(+) Operator Overloading
NUM operator +(NUM &obj)
{
NUM x;  //create another object
x.n=this->n + obj.n;
return (x); //return object
}
};
int main()
{
NUM num1,num2,sum;
num1.getNum(10);
num2.getNum(20);

//add two objects
sum=num1+num2;

sum.dispNum();
cout << endl;
return 0;
} 

这些是我得到的错误。

main.cpp:7:14: error: ‘vector’ in namespace ‘std’ does not name a template type
std::vector<int> n ;
^~~~~~
main.cpp:11:26: error: ‘std::vector’ has not been declared
void getNum(std::vector<int> x)
^~~~~~
main.cpp:11:32: error: expected ‘,’ or ‘...’ before ‘<’ token
void getNum(std::vector<int> x)
^
main.cpp: In member function ‘void NUM::getNum(int)’:
main.cpp:13:13: error: ‘n’ was not declared in this scope
n=x;
^
main.cpp:13:15: error: ‘x’ was not declared in this scope
n=x;
^
main.cpp: In member function ‘void NUM::dispNum()’:
main.cpp:18:38: error: ‘n’ was not declared in this scope
cout << "Number is: " << n;
^
main.cpp: In member function ‘NUM NUM::operator+(NUM&)’:
main.cpp:24:15: error: ‘class NUM’ has no member named ‘n’
x.n=this->n + obj.n;
^
main.cpp:24:23: error: ‘class NUM’ has no member named ‘n’
x.n=this->n + obj.n;
^
main.cpp:24:31: error: ‘class NUM’ has no member named ‘n’
x.n=this->n + obj.n;
#include<iostream>
#include <vector>
#include <algorithm>
using namespace std;
class NUM
{
private:
std::vector<int> n ;
public:
//function to get number
void getNum(std::vector<int> x)
{
n=x;
}
//function to display number
void dispNum(void)
{
cout << "Number is: " <<endl;
for_each(n.begin(),n.end(),[](int i){cout <<i<<endl;});
}
//add two objects - Binary Plus(+) Operator Overloading
NUM operator +(NUM &obj)
{
NUM x;  //create another object
//x.n=this->n + obj.n;
if(this->n.size() == obj.n.size())
for (int i = 0; i < this->n.size(); ++i) {
x.n.push_back(this->n.at(i)+obj.n.at(i));
}

return x; //return object
}
};
int main()
{
NUM num1,num2,sum;
num1.getNum({10});
num2.getNum({20});
//add two objects
sum=num1+num2;
sum.dispNum();
cout << endl;
return 0;
}

您没有包含矢量标头,这会导致错误

#include <iostream>
#include <vector>
using namespace std;

这将解决错误。
或者你也可以使用

#include <bits/stdc++.h>
using namespace std;

这将一次包含整个标准库。

最新更新