简体   繁体   English

如何从C ++中的函数返回向量?

[英]How can I return a vector from a function in c++?

vector<double> function(vector<double> &X){
    vector<double> data2;
    for (int i = 0; i < X.size(); i++){
        data2.push_back(2*X[i]);
    }
    return data2;
}
int main(){
    vector<double> data;
    for (int i = 1; i <= 10; i++){
        data.push_back(i);
    }
    for (int i = 0; i < data.size(); i++){
        cout << function(data) << endl;
    }
return 0;
}

Basically, for a given artificially created vector of "data" for data[i] = i, I want a function such that it multiplies each element of the vector by 2, then print the result. 基本上,对于给定的数据[i] = i的“数据”人工创建的矢量,我想要一个函数,使其将矢量的每个元素乘以2,然后打印结果。 However, I can't seem to understand what I did wrong. 但是,我似乎无法理解我做错了什么。

The function returns a std::vector which is a kind of container. function返回std::vector ,这是一种容器。 And we can't use std::cout to print the elements of std::vector . 而且我们不能使用std::cout打印std::vector的元素。
We should go into the container to get elements and print them. 我们应该进入容器以获取元素并进行打印。
Like this: 像这样:

data2 = function(data);
for (int i = 0; i < data2.size(); i++)
{
        cout << data2[i]<< endl;
}

First of all, to simplify things, let's write a simple function that prints out the contents of a vector. 首先,为简化起见,让我们编写一个简单的函数来打印出向量的内容。 Now, to see what a vector looks like we can just call the function and see what it looks like. 现在,要查看向量的外观,我们可以调用该函数并查看其外观。

template <typename T>
void printVector(const vector<T> &input){
    unsigned sz = input.size();
    cout<<"========"<<endl;
    for(unsigned i=0; i<sz; i++){
        cout<<input[i]<<endl;
    }
    cout<<"========"<<endl;
}

Remember, if a function takes an object of a generics class (such as std::vector< T >), you need to specify that it is a template function. 请记住,如果函数采用泛型类的对象(例如std :: vector <T>),则需要指定它是模板函数。

Now, back to your question. 现在,回到您的问题。 I am assuming that you do not want change the values of data itself, because you declared data2 . 我假设您不想更改data本身的值,因为您声明了data2

Then you have two options (if I understand the problem you are trying to solve). 然后,您有两个选择(如果我了解您要解决的问题)。

The first option is to write a function that returns a vector. 第一种选择是编写一个返回向量的函数。

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
vector<T> doublingFunc(const vector<T> &input){
    vector<T> output;
    /* it is good practice
       to catch the size of the vector
       once so that you aren't calling
       vector::size() each go through
       of the loop, but it is no big deal
    */
    unsigned sz = input.size();
    for(unsigned i=0; i<sz; i++){
        output.push_back(2*input[i]);
    }
    return output;
}

template <typename T>
void printVector(const vector<T> &input){
    unsigned sz = input.size();
    cout<<"========"<<endl;
    for(unsigned i=0; i<sz; i++){
        cout<<input[i]<<endl;
    }
    cout<<"========"<<endl;
}

int main(){
    vector<double> data;

    for(int i=1; i<10; i++){
        data.push_back((double) i);
       //technically, the cast in unnecessary
    }

    printVector(data);

    vector<double> data2 = doublingFunc(data);

    printVector(data2);

    return 0;
}

The second option is to write a function that dynamically allocates a new vector and then return a pointer to it. 第二种选择是编写一个函数,该函数动态分配新的向量,然后返回指向它的指针。

#include <iostream>
#include <vector>

using namespace std;

template <typename T>
vector<T>* doublingFunc(const vector<T> &input){
    vector<T>* output = new vector<T>();
    /* it is good practice
       to catch the size of the vector
       once so that you aren't calling
       vector::size() each go through
       of the loop, but it is no big deal
    */
    unsigned sz = input.size();
    for(unsigned i=0; i<sz; i++){
        output->push_back(2*input[i]);
    }
    return output;
}

template <typename T>
void printVector(const vector<T> &input){
    unsigned sz = input.size();
    cout<<"========"<<endl;
    for(unsigned i=0; i<sz; i++){
        cout<<input[i]<<endl;
    }
    cout<<"========"<<endl;
}

int main(){
    vector<double> data;

    for(int i=1; i<10; i++){
        data.push_back((double) i);
    }

    printVector(data);

    vector<double>* data2 = doublingFunc(data);

    /*this function takes a reference to a vector,
     so we need to dereference the pointer
   */
    printVector(*data2);

    //remember to delete dynamically allocated variables
    delete data2;
    return 0;
}

Of course, if you just want to print out twice the value of all entries in a vector, you can just use the function: 当然,如果您只想输出矢量中所有条目的值的两倍,则可以使用以下函数:

template <typename T>
void printDouble(const vector<T> &input){
    unsigned sz = input.size();
    cout<<"========"<<endl;
    for(unsigned i=0; i<sz; i++){
        cout<<2 * input[i]<<endl;
    }
    cout<<"========"<<endl;
}

This might be a lot of new stuff for you, as you seem new to c++. 对于您来说,这可能是很多新东西,因为您似乎对c ++陌生。 I suggest reading through this website. 我建议阅读网站。

For std::cout to print an std::vector, you have to overload the stream insertion operator (<<) for it. 对于std :: cout要输出std :: vector,您必须为其重载流插入运算符(<<)。

eg 例如

std::ostream& operator << ( std::ostream& os, const std::vector<double>& v )
{
    os << "{ ";
    for ( const auto& i : v )
    {
        os << i << ' ';
    }
    os << "}";
    return os;
}

For printing the contents of a container, you can use C++11 range-for loop as used in the above example. 要打印容器的内容,可以使用上面示例中使用的C ++ 11 range-for循环

You can also use std::copy algorithm for this overload or use it directly like this: 您也可以对这种重载使用std :: copy算法,或像这样直接使用它:

std::ostream& operator << ( std::ostream& os, const std::vector<double>& v )
{
    os << "{ ";
    std::copy( begin(v), end(v), std::ostream_iterator<double>( os, " " ) );
    os << "}";
    return os;
}

In your code, you can simply use function to operate on the values of the vector and then print it like this: 在您的代码中,您可以简单地使用function对向量的值进行运算,然后按如下所示进行打印:

void multiplyBy2( vector<double>& v )
{
    for ( auto& i : v )
    {
        i *= 2;
    }
}

int main( void )
{
    vector<double> v;
    // ...
    multiplyBy2( v );
    std::cout << v << std::endl;

    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM