PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, July 6, 2022

[FIXED] How can I return vector by reference in C++

 July 06, 2022     c++, pass-by-reference, vector     No comments   

Issue

I want to make the function that returns a vector by reference. But the returned vector(returned_v) is not same as vec.v, but a copied vector. It means the vector is returned by value. How can I get the referenced vector from vector_reference()?

class Vec {
  public:
    std::vector<int> v = {1, 2, 3};
    std::vector<int>& vector_reference() {
        return v;
    }
};

int main() {
    Vec vec;
    std::vector<int> returned_v = vec.vector_reference();
    returned_v.clear();
    std::cout << returned_v.size() << std::endl; // result: 0
    std::cout << vec.v.size() << std::endl; // result: 3

    return 0;
}

Solution

returned_v is an independent object which gets copied from the return value of vec.vector_reference(). You should declare it as reference too.

std::vector<int>& returned_v = vec.vector_reference();


Answered By - songyuanyao
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing