'push_back element to vector in class object isn't working
- classObject and vector within it.
- I made a vector of classObject and function that searches classObject with a given int id.
- Wanted to search certain classObject from listClass and add "apple" inside its wordList but failed. (assume listClass contains classObject with id 1)
class classObject {
public:
int id;
vector<string> wordList;
};
vector<classObject> listClass;
classObject getClassById(int _i) {
for(auto e : listClass) {
if(e.id == _i) return e;
}
}
classObject example = getClassById(1);
example.wordList.push_back("apple");
cout << getClassById(1).wordList.size();
// returns 0. Supposed to be 1 (added apple)
Tried to use pointer
classObject* getClassById(int _i) {
for(auto e : listClass) {
if(e.id == _i) return &e;
}
}
classObject example = *getClassById(1);
example.wordList.push_back("apple");
Still not working. help!
Solution 1:[1]
classObject example
is a copy, you need to use classObject& example
to store a reference and change getClassById
to return a reference too:
classObject& getClassById(int _i) {
for(auto& e : listClass) {
if(e.id == _i) return e;
}
}
classObject& example = getClassById(1);
Now we're left with the problem that getClassById
doesn't always return a value. You probably have three options to solve this:
- Throw an exception at the end of
getClassById
when no value is found - Return some default object
- Change the return from a reference to a pointer and return a null pointer
For either of the last two options you'll need to change the calling code to check for the special/null value.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Alan Birtles |