William Duron
William Duron

Reputation: 33

Vector Appending

so far this is my code what i am trying to do is say the user inputs 1 2 3 and then presses -1, he or she will be asked to input another set of numbers say 9 8 7, what my programs is suppose to do is display them out as such 1 2 3 9 8 7, but rather it is displaying them like this 6 6 6 6 6 6, basically it counts how many numbers there are and displays that amount of numbers with that number. So can anyone help me out here, how do i make it so that it displays the two sets of numbers combined?

#include <iostream>

#include <vector>

using namespace std;

vector<int> append(vector<int> a, vector<int> b)
{
    int n = a.size();
    int m = b.size();
    vector<int> c(n + m);
    int i;

    for (i = 0; i < n; i++)
        c[i] = a[i];

    for (i = 0; i < m; i++)
        c[n + i] = b[i];

    return c;
}

int main()
{
    cout << "Please enter a set of numbers, insert -1 when done.\n";
    vector<int>a;
    bool more = true;
    while (more)
    {
        int n;
        cin >> n;
        if (n == -1)
            more = false;
        else
            a.push_back(n);
    }


    cout << "Please enter another set of numbers, insert -1 when done.\n";
    vector<int>b;
    more = true;
    while (more)
    {   
        int m;
        cin >> m;
        if (m == -1)
            more = false; 
        else 
            b.push_back(m);
    }

    vector<int>d = append(a,b);
    {

        int i;
        for (i= 0; i < d.size(); i++)

        cout << d.size() << "\n";
    } 
}

Upvotes: 0

Views: 134

Answers (2)

Fantastic Mr Fox
Fantastic Mr Fox

Reputation: 33864

It is because when you are printing it, you are printing d.size instead of d[i].

cout << d.size() << "\n";

Would needs to be:

cout << d[i] << endl;

Upvotes: 0

Jace
Jace

Reputation: 3072

That's because at the end you're printing the size, not the value:

cout << d.size() << "\n";

Should be:

cout << d[i] << "\n";

Upvotes: 3

Related Questions