c++ - Declaration of Vectors -
vectors size dynamically, why giving seg fault:
#include <iostream> #include <string> #include <vector> using namespace std; int main(){ vector<int> vectorofints; vectorofints[0] = 3; }
what i'm trying declare vector in class.
#include <iostream> #include <string> #include <vector> using namespace std; class directory{ public: string name; int maxindex; vector<directory> subdirectories; void addsubdirectory(string x){ directory newsubdirectory(x); subdirectories[maxindex++] = newsubdirectory; } directory(string x){ name = x; maxindex = 0; } }; int main(){ directory root("root"); root.addsubdirectory("games"); }
but gives seg fault.
vectors don't resize entirely automatically. use push_back
or resize
change size of vector @ run-time, vector not automatically resize based on index use--if index beyond current size, undefined behavior.
in demo code, this:
vector<int> vectorofints(1); vectorofints[0] = 3;
alternatively, since you're adding 3
end of existing data (or nonexistent data, in case) use push_back
(or emplace_back
):
vector<int> vectorofints; vectorofints.push_back(3);
it looks same basic approach work real code well. simplifies things bit, since don't need explicitly track maxindex you've done.
Comments
Post a Comment