Q:

Determine if there are any errors in the following programs and, if so, correct the error(s)

0

Determine if there are any errors in the following programs and, if so, correct the error(s):

(a)

vector<int> vec; list<int> lst; int i;
while (cin >> i)
 lst.push_back(i);
copy(lst.cbegin(), lst.cend(), vec.begin());

(b)

vector<int> vec;
vec.reserve(10); // reserve is covered in § 9.4 (p. 356)
fill_n(vec.begin(), 10, 0);

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

(a)

    vector<int> vec; list<int> lst; int i;
    while (cin >> i)
      lst.push_back(i);
    vec.resize(lst.size());
    // We must resize the vector before copying the elements so that it can hold
    // at least the same amount of elements.
    copy(lst.cbegin(), lst.cend(), vec.begin());

(b)

    vector<int> vec;
    //vec.reserve(10);
    // Reserve only allocate memory, while not add elements to the vector, but
    // the function `fill_n` need `n` elements in container.
    vec.resize(10);  // Use `resize` to add elements
    //fill_n(std::back_inserter(vec), 10, 0);
    // Or use `back_inserter` to add elements
    fill_n(vec.begin(), 10, 0);

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

Similar questions


need a help?


find thousands of online teachers now