Rick Huenink
Rick Huenink

Reputation: 21

Program to initialize a vector from an array of ints. Cout is getting error?

Is the first element of arr1 getting added? cout is giving me an error. What am I doing wrong?

#include <iostream>
using std::cin; using std::cout; using std::endl;

#include <string>
using std::string;

#include <vector>
using std::vector;

#include <cstddef>
using std::size_t;

int main ()
{
    vector <int> ivec1; //defines a vector named ivec1 to hold values not yet defined
    int arr1 [5] = {10, 20, 30 , 40, 50}; // defines array named arr1 with 5 values
    ivec1.push_back (arr1 [0]);
    cout << ivec1 << endl;

    return 0;
}

Upvotes: 1

Views: 141

Answers (2)

pmr
pmr

Reputation: 59831

The answer is quite simple: The operation you are invoking is simply not defined. The IO stream library is blissfully unaware of C++ standard library containers (besides std::string) and does not know how to print them. You will need to do that yourself.

std::vector<int> v;
for(auto& x : v)
  std::cout << v << " "; // print each element
std::cout << std::endl; // and a linebreak

Upvotes: 1

Mikhail Payson
Mikhail Payson

Reputation: 921

I guess cout is not able to work with vectors. I'd implement something like this (I'm sorry for my C++ I didn't write in C++ since 2006...

#include "stdafx.h"

#include <iostream>
using std::cin; using std::cout; using std::endl;

#include <string>
using std::string;

#include <vector>
using std::vector;

#include <cstddef>
using std::size_t;

void fillVector(int output[], vector<int>& input, int size)
{
    for(int i=0;i<size; i++)
    {
        input.push_back(output[i]);
    }
}

void printVector(vector<int>& input)
{
    for(int i=0; i<input.size(); i++)
    {
        cout << input.at(i);
        if(i!=input.size()-1)
        {
            cout << ",";
        }
    }
    cout << endl;
}


int main ()
{
    vector <int> ivec1; //defines a vector named ivec1 to hold values not yet defined
    int arr1 [5] = {10, 20, 30 , 40, 50}; // defines array named arr1 with 5 values
    int sz = sizeof(arr1) / sizeof(int);

    fillVector(arr1, ivec1, sz);

    printVector(ivec1);

    return 0;
}

Upvotes: 0

Related Questions