Dlean Jeans
Dlean Jeans

Reputation: 996

Alternative to array of references in c++?

Is there any alternative to array of references since it's not allowed in C++? C++ Standard 8.3.2/4:

There shall be no references to references, no arrays of references, and no pointers to references.

EDIT: I'm writing two classes Cuboid and Quad to draw a cuboid in OpenGL. You set the position, the size of the cuboid, it will calculate 8 vertices' positions stored in an array of sf::Vector3<> in SFML. Then those will be passed in an array of pointers, as you answered, in four Quad to draw. So I don't wanna copy 8 vertices to 24 vertices since there's 6 faces (Quad) in a cuboid, each face has 4 vertices. I hardly ever use pointer.

Upvotes: 0

Views: 1601

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311010

You can use std::reference_wrapper declared in header <functional>. Here is a demonstrative program:

#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>
#include <iterator>

int main()
{
    int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    std::vector<std::reference_wrapper<int>> v( std::begin( a ), std::end( a ) );

    for ( int x : v ) std::cout << x << ' ';
    std::cout << std::endl;

    std::for_each( v.begin(), v.end(), []( auto &r ){ r.get() *= 2; } );

    for ( int x : a ) std::cout << x << ' ';
    std::cout << std::endl;

    std::sort( v.begin(), v.end(), std::greater<int>() );

    for ( int x : v ) std::cout << x << ' ';
    std::cout << std::endl;

    for ( int x : a ) std::cout << x << ' ';
    std::cout << std::endl;
}

The program output is

1 2 3 4 5 6 7 8 9 
2 4 6 8 10 12 14 16 18 
18 16 14 12 10 8 6 4 2 
2 4 6 8 10 12 14 16 18 

Upvotes: 1

Barth
Barth

Reputation: 15715

You could use an array of pointers :

Foo *array[10]; // array of 10 Foo pointers

It depends a lot on what you want to do though.

Upvotes: 4

sirgeorge
sirgeorge

Reputation: 6541

You could use an array of pointers, or even better, a vector of smart pointers:

using namespace std;
class MyClass
{
    public:
        MyClass() {}
        void foo() {}
    ....
};
vector<shared_ptr<MyClass>> V;
V.push_back(make_shared<MyClass>());
V[0]->foo();

Upvotes: 0

Related Questions