如何实现容量为100的部分填充的整数数组?

时间:2019-12-16 20:09:43

标签: c++

a)用8个整数变量初始化数组。

b)创建具有恒定参数的输出函数。

c)创建一个getIndex函数,该函数返回元素的索引  或-1(如果该元素不存在)。

d)创建一个removeElement函数,该函数删除指定的元素  从数组。此函数应使用getIndex函数  找到要删除的元素。

示例输出

数组:90 75 83 99 100 21 55 73

删除75:90 83 99 100 21 55 73

删除55:90 83 99 100 21 73

1 个答案:

答案 0 :(得分:0)

所以,八天后没有答案。

解决方案非常简单。因此,我将不赘述。

请在下面查看答案

#include <iostream>
#include <vector>
#include <algorithm>
#include <iterator>

// Show all values of the vector in one line
void output(const std::vector<int>& v) {
    std::copy(v.begin(), v.end(), std::ostream_iterator<int>(std::cout, " ")); std::cout << "\n";
}

// Search for an element and return its index
int getIndex(std::vector<int>& v, const int& i) {
    std::vector<int>::iterator pos = std::find(v.begin(), v.end(), i);
    return (pos != v.end()) ? std::distance(v.begin(), pos) : -1;
}

// Remove a given element from the vector
void remove(std::vector<int>& v, const int& i) {
    int pos = getIndex(v, i);
    v.erase(std::next(v.begin(), pos));
}

int main() {
    // Define vector
    std::vector<int> array{ 90, 75, 83, 99, 100, 21, 55, 73 };
    array.resize(100);

    // Remove Element and show output
    remove(array, 75);
    output(array);

    // Remove Element and show output
    remove(array, 55);
    output(array);

    return 0;
}