1

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};

???

Tez
  • 517
  • 1
  • 7
  • 16

2 Answers2

2

You can avoid creating the temporary object while building your vector using 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);
}
Masked Man
  • 1
  • 7
  • 40
  • 80
0

If you are using a C++11 compiler, compile the .cpp file using g++ -std=c++11. Also, remove typedef from the definition of the struct duo.

Otherwise you can create a parameterized constructor for duo and then use the constructor for push_back the duo objects into the vector.

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.

bolov
  • 72,283
  • 15
  • 145
  • 224
shauryachats
  • 9,975
  • 4
  • 35
  • 48
  • If you are on Linux, open the Terminal; If on Windows, open Command Prompt. Reach to the directory where your .cpp file is present. Let the .cpp file name be x.cpp . So, write `g++ -std=c++11 x.cpp -o x` if on Linux **or** `g++ -std=c++11 x.cpp -o x.exe` if on Windows. You will have no errors in compilation then. – shauryachats Jan 27 '15 at 07:38