Home > OS >  How can I set class member variable correctly from vector in C
How can I set class member variable correctly from vector in C

Time:07-28

I'm trying to set a class member variable from STL vector in C .

But it doesn't work the way I want it to. The variable doesn't change, The variable is the same like before.

Am I programming in the wrong way?

Here's the code.

#include <iostream>
#include <vector>
using namespace std;

class Test {
private:
  std::string name;

public:
  Test();
  Test(std::string p_name);
  std::string getName();
  void setName(std::string p_name);
};

Test::Test() { name = ""; }

Test::Test(std::string p_name) : name(p_name) {}

std::string Test::getName() { return name; }

void Test::setName(std::string p_name) { name = p_name; }

int main() {
  // Initializing vector with values
  vector<Test> tests;

  for (size_t i = 0; i < 10; i  ) {
    tests.push_back(Test());
  }

  for (Test test : tests) {
    cout << test.getName() << endl;
    test.setName("a");
  }

  for (Test test : tests) {
    cout << test.getName() << endl;
  }

  return 0;
}

This is the result:

> ./main




















> 

Why It doesn't work, and how to fix it?

CodePudding user response:

You're copying the elements from the vector each time you iterate through it in your loop.

Try changing your code to something like this:

for (auto& test : myTests) {
    test.setName("My new name");
}

In this case, the ampersand (&) marks the variables as a reference, which means you can manipulate it directly.

The way your code is written, you're using the copy-constructor to construce a new object.

You can circumvent this, by adding something like:

public:
    explicit Test(const Test&) = delete;

to your class. This will prevent the copying of the object, which will reduce the likelihood of these types of errors.

  • Related