如何引用向量作为参数

how to reference a vector as an argument

本文关键字:向量 参数 引用 何引用      更新时间:2023-10-16

有人能帮我加法器功能吗?我认为这几乎是正确的,然而,我需要帮助知道正确的方式来传递我的矢量,我不知道如何做到这一点。提前感谢!

#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);
}