小编use*_*585的帖子

不懂矢量 C++

#include <iostream>
#include <vector>

using namespace std;

void SaveNumbers(vector<int> numbers);

int main()
{
    vector<int> numbers;
    SaveNumbers(numbers);

    cout << "FROM MAIN FUNCTION:" << endl;

    for(int i = 0; i < 5; i++)
    {
        cout << numbers.at(i) << " ";
    }
    cout << endl;
    return 0;
}

void SaveNumbers(vector<int> numbers)
{
    for(int i = 0; i < 5; i++)
    {
        numbers.push_back(i + 1);
    }
    cout << "FROM FUNCTION: " << endl;
    for(int i = 0; i < 5; i++)
    {
        cout << …
Run Code Online (Sandbox Code Playgroud)

c++ vector

0
推荐指数
1
解决办法
83
查看次数

C++ 中的动态数组实现

我正在尝试使用 C++ 实现动态数组。但是,我的resize()功能似乎无法正常工作。没有错误或警告。我做了一些研究并尝试查看互联网上找到的其他实现,但无法解决该问题。我把我的代码放在下面。

#include <iostream>

class Array
{
private:
    int* arr;
    int size = 0;
    int capacity = 1;

public:
    Array() { arr = new int[capacity]; }

    Array(int capacity)
        :
        capacity(capacity)
    {
        arr = new int[capacity];
    }

    int length() const { return size; }

    bool is_empty() const { return (length() == 0); }

    int get(int index) const { return arr[index]; }

    void set(int index, int value) { arr[index] = value; }

    void resize()
    {
        capacity *= 2;
        int* …
Run Code Online (Sandbox Code Playgroud)

c++ class definition member-functions dynamic-memory-allocation

0
推荐指数
1
解决办法
1135
查看次数