如何引用向量作为参数
how to reference a vector as an argument
有人能帮我加法器功能吗?我认为这几乎是正确的,然而,我需要帮助知道正确的方式来传递我的矢量,我不知道如何做到这一点。提前感谢!
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
std::vector<std::string> Adder(std::vector<std::string> myVector);
int main()
{
std::vector<std::string> inventory;
std::vector<std::string>::iterator myIter;
inventory.push_back("sword");
inventory.push_back("bow");
inventory.push_back("shield");
inventory.push_back("armor");
for (myIter = inventory.begin(); myIter != inventory.end(); myIter++)
{
std::cout << *myIter << "n";
}
Adder(inventory);
for (myIter = inventory.begin(); myIter != inventory.end(); myIter++)
{
std::cout << *myIter << "n";
}
return 0;
}
std::vector<std::string> Adder(std::vector<std::string> myVector)
{
std::string prompt;
std::cout << "Enter a new item to add to your inventory: ";
std::cin >> prompt;
myVector.insert(myVector.begin(), prompt);
return myVector;
}
std::vector<std::string> Adder(std::vector<std::string> myVector);
Adder
函数取vector
的值。这意味着将vector
的副本传递给该函数,并且您所做的任何修改显然不会被main()
中的副本看到。
你应该把函数改成:
void Adder(std::vector<std::string>& myVector);
现在实参被引用了,你对它所做的任何修改都是对原始对象所做的。
另一种选择是保持函数不变,并将main()
中的vector
替换为函数返回的值。
std::vector<std::string> inventory;
// ... stuff
inventory = Adder(inventory); // the original is replaced with the return value
// rest of your code
在声明方法时使用Adder(std::vector<std::string> &myVector)
,这样它将使用vector的引用,而不是像您所做的那样使用副本。
当你不使用&只有副本获得新值。还可以使用指针
#include <iostream>
#include <string>
#include <algorithm>
#include <vector>
void Adder(std::vector<std::string> &myVector);
int main()
{
std::vector<std::string> inventory;
std::vector<std::string>::iterator myIter;
inventory.push_back("sword");
inventory.push_back("bow");
inventory.push_back("shield");
inventory.push_back("armor");
for (myIter = inventory.begin(); myIter != inventory.end(); myIter++)
std::cout<<*myIter<<"n";
Adder(inventory);
for (myIter = inventory.begin(); myIter != inventory.end(); myIter++)
std::cout<<*myIter<<"n";
return 0;
}
void Adder(std::vector<std::string> &myVector)
{
std::string prompt;
std::cout<<"Enter a new item to add to your inventory: ";
std::cin>>prompt;
myVector.insert(myVector.begin(), prompt);
}
相关文章:
- 我使用向量来创建类对象列表.初始化向量时如何使用参数调用构造函数?
- 标准::向量声明中使用的模板参数
- 使用 C++ 将命令行参数拆分为参数/向量
- 如何在 c++ 中定义接受不同参数类型的函数向量?
- 如何将向量中的可变参数转换为参数的持有者?
- C++向量默认为成员参数
- 使用向量初始化参数化构造函数的对象数组
- 有什么方法可以将具有不同模板参数的模板类实例放入向量中?
- OpenCL 是否支持向量作为内核参数?
- 使用并行参数向量调用元素向量的成员函数
- 如何将子类作为函数的参数传递给期望基类,然后将该对象传递到指向这些抽象类对象的指针向量中?
- 将不同类型的模板参数包提取到双精度向量中会产生警告
- 如何从 node-ffi 调用 c++ 中以结构向量作为参数的方法?
- 将任意模板向量作为函数参数C++传递
- 为什么我们需要在优先级队列声明中添加一个向量作为参数?
- 如何使用非特异性类型制作向量参数
- C++ 类中的向量参数
- 采用向量参数的函数模板回文
- 将向量参数为空传递
- C++和python:向量参数的TypeError解析