Std :: Vector不更改类内的数据

时间:2018-12-22 21:47:54

标签: c++ vector std

我正在使用向量做一些事情,并且试图编写一个可以循环通过向量并对向量内的对象执行操作的程序。我已经阅读了很多有关最少代码的文章,所以我已经编写了这个小应用程序来说明问题。

该程序的输出为:

Element 1 is equal to 2
Element 2 is equal to 4
Element 1 is equal to 2
Element 2 is equal to 4
Press any key to continue...

输出应为:

Element 1 is equal to 2
Element 2 is equal to 4
Element 1 is equal to 7
Element 2 is equal to 9
Press any key to continue...

为什么我没有达到期望的输出?

#include <vector>
#include <iostream>

// Some object
class A {
public:
    A(int data)
        : data(data)
    {}

    int data;
};

class B {
public:
    // A function that adds a new 'A' object to the vector in class b
    void push_back_to_vector(A &element);
    // A function that changes the data of the objects stored in vector_of_a
    void add_to_vector();
    // A vector to hold objects of A
    std::vector<A> vector_of_a;
};

void B::push_back_to_vector(A &element) {
    vector_of_a.push_back(element);
}

void B::add_to_vector() {
    for (size_t i = 0; i < vector_of_a.size(); i++) {
        // Add five to all the elements in the vector
        vector_of_a[i].data += 5;
    }
}

int main() {
    A element_1(2);
    A element_2(4);

    B b;
    b.push_back_to_vector(element_1);
    b.push_back_to_vector(element_2);

    std::cout << "Element 1 is equal to " << element_1.data << std::endl;
    std::cout << "Element 2 is equal to " << element_2.data << std::endl;

    // This should change element_1.data to 7 and element_2.data to 9
    b.add_to_vector();

    std::cout << "Element 1 is equal to " << element_1.data << std::endl;
    std::cout << "Element 2 is equal to " << element_2.data << std::endl;

    system("pause");
    return 0;
}

1 个答案:

答案 0 :(得分:1)

push_back复制新元素。如果您想做自己想做的事情,则需要存储指向A的指针,而不仅仅是A

基本上,您的代码就是这样:

A element_1(2);
A element_2(4);

std::cout << "Element 1 is equal to " << element_1.data << std::endl;
std::cout << "Element 2 is equal to " << element_2.data << std::endl;

std::cout << "Element 1 is equal to " << element_1.data << std::endl;
std::cout << "Element 2 is equal to " << element_2.data << std::endl;

system("pause");
return 0;

B相关的所有内容均无效。试试这个:

class B {
public:
    // A function that adds a new 'A' object to the vector in class b
    void push_back_to_vector(A *element);
    // A function that changes the data of the objects stored in vector_of_a
    void add_to_vector();
    // A vector to hold objects of A
    std::vector<*A> vector_of_a;
};

void B::push_back_to_vector(A* element) {
    vector_of_a.push_back(element);
}

void B::add_to_vector() {
    for (size_t i = 0; i < vector_of_a.size(); i++) {
        // Add five to all the elements in the vector
        vector_of_a[i]->data += 5;
    }
}

并传递指针:

b.push_back_to_vector(&element_1);
b.push_back_to_vector(&element_2);

当然,请注意您在B中指向的堆栈上对象的生命周期。