简体   繁体   English

不能将struct类型的元素添加到vector吗?

[英]Can't add elements of a struct type to vector?

I'm trying to add two values into a vector of a custom type, without creating a variable of that type. 我试图将两个值添加到自定义类型的向量中,而不创建该类型的变量。

typedef struct duo{
    int uniqueID; 
    double data; 
};

vector<duo> myVector;
myVector.push_back({1,1.0});

But it won't allow it?? 但这是不允许的??

The only way I can get it to work is if I create the variable, but feels tedious... 我可以使它工作的唯一方法是创建变量,但感到乏味...

vector<duo> myVector;
duo temp = {1,1.0};
myVector.push_back(temp);

Also... why can't I do this? 还有...我为什么不能这样做?

duo temp;
temp = {1,1.0}; 

but I can do this: 但我可以这样做:

duo temp = {1,1.0};

??? ???

You can avoid creating the temporary object while building your vector using std::vector::emplace_back() . 使用std :: vector :: emplace_back()构建矢量时,可以避免创建临时对象。

Below is the code sample. 下面是代码示例。

class duo {
public:
    duo(int uniqueID_, double data_)
        : uniqueID(uniqueID_)
        , data(data_) {}

private:        
    int uniqueID; 
    double data; 
};


int main() {
    vector<duo> myVector;
    myVector.emplace_back(1, 1.0);
}

If you are using a C++11 compiler, compile the .cpp file using g++ -std=c++11 . 如果使用的是C ++ 11编译器,请使用g++ -std=c++11编译.cpp文件。 Also, remove typedef from the definition of the struct duo . 另外,从struct duo的定义中删除typedef

Otherwise you can create a parameterized constructor for duo and then use the constructor for push_back the duo objects into the vector. 否则,您可以为duo创建一个参数化的构造函数,然后将该构造函数用于push_backduo对象放入向量中。

Code: 码:

struct duo {
    int uniqueID; 
    double data; 
    duo(int _uniqueID, double _data) : uniqueID{_uniqueID}, data{_data} {}
};

vector<duo> myVector;
myVector.push_back(duo(1,1.0)); //This compiles.

Hope that helped. 希望能有所帮助。

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

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