爲何不能創建參考向量?

當我這樣作時: ios

std::vector<int> hello;

一切正常。 可是,當我將其設爲參考向量時: c++

std::vector<int &> hello;

我收到可怕的錯誤,例如 app

錯誤C2528:「指針」:指向引用的指針不合法 ui

我想將一堆對結構的引用放到一個向量中,這樣我就沒必要插手指針了。 爲何vector對此大發脾氣? 我惟一的選擇是使用指針向量嗎? spa


#1樓

是的,您能夠尋找std::reference_wrapper ,它模仿引用但能夠分配,也能夠「從新放置」 指針


#2樓

Ion Todirel已經使用std::reference_wrapper提到了答案「是」從C ++ 11開始,咱們提供了一種從std::vector檢索對象並使用std::remove_reference刪除引用的std::remove_reference 。 下面給出了使用g++clang編譯帶有選項的示例
-std=c++11併成功執行。 c++11

#include <iostream>
#include <vector>
#include<functional>

class MyClass {
public:
    void func() {
        std::cout << "I am func \n";
    }

    MyClass(int y) : x(y) {}

    int getval()
    {
        return x;
    }

private: 
        int x;
};

int main() {
    std::vector<std::reference_wrapper<MyClass>> vec;

    MyClass obj1(2);
    MyClass obj2(3);

    MyClass& obj_ref1 = std::ref(obj1);
    MyClass& obj_ref2 = obj2;

    vec.push_back(obj_ref1);
    vec.push_back(obj_ref2);

    for (auto obj3 : vec)
    {
        std::remove_reference<MyClass&>::type(obj3).func();      
        std::cout << std::remove_reference<MyClass&>::type(obj3).getval() << "\n";
    }             
}

#3樓

正如其餘註釋所建議的那樣,您僅限於使用指針。 可是,若是有幫助,這是一種避免直接面對指針的技術。 code

您能夠執行如下操做: 對象

vector<int*> iarray;
int default_item = 0; // for handling out-of-range exception

int& get_item_as_ref(unsigned int idx) {
   // handling out-of-range exception
   if(idx >= iarray.size()) 
      return default_item;
   return reinterpret_cast<int&>(*iarray[idx]);
}

#4樓

TL; 博士

像這樣使用std::reference_wrapperrem

#include <functional>
#include <string>
#include <vector>
#include <iostream>

int main()
{
    std::string hello = "Hello, ";
    std::string world = "everyone!";
    typedef std::vector<std::reference_wrapper<std::string>> vec_t;
    vec_t vec = {hello, world};
    vec[1].get() = "world!";
    std::cout << hello << world << std::endl;
    return 0;
}

演示版

長答案

正如標準所建議的 ,對於包含類型T對象的標準容器XT必須是ErasableX Erasable

Erasable表示如下表達式格式正確:

allocator_traits<A>::destroy(m, p)

A是容器的分配器類型, m是分配器實例, p是類型*T的指針。 有關Erasable定義,請參見此處

默認狀況下, std::allocator<T>用做向量的分配器。 使用默認分配器,該要求等效於p->~T()的有效性(請注意, T是引用類型,而p是指向引用的指針)。 可是, 指向引用的指針是非法的 ,所以該表達式的格式不正確。


#5樓

這是C ++語言的缺陷。 您不能使用引用的地址,由於嘗試這樣作會致使引用對象的地址,所以您永遠沒法得到指向引用的指針。 std::vector可以使用指向其元素的指針,所以須要可以存儲指向的值。 您將不得不使用指針。

相關文章
相關標籤/搜索