Hi, I was trying to create a vector of strings with size 100 using the following code:
vector<string> arr(100);
However, this line gives me an error - expected parameter declarator. Why is this an error, and how do I rectify it? I haven't experienced this error while working with vectors of integers, bools, etc.
You could either:
- not use a fixed-size vector (this would be my preference);
- use a different type of container;
- size it in the class constructor;
- bizarrely, you could do: vector<string> Contacts = vector<string>(100);
but I don't understand why this compiles and the original didn't.
The reason againtry's code works is because the declaration is outside the class, to make it work in the class you need to use braces instead of parentheses.
Also note that the zero argument constructor is created by default so there is no need to create this constructor as a do nothing function.
@OP
Well, now that the vector is sorted there are a number of problems going way beyond that now we know the context. And you will get more use/fun out of your phonebook:
1. Why specify the size anyway? Let the <vector> work that out.
2. Why select a vector? A <map> could be better
3. Why just store names? Why not Person objects with a name and phone-number at least?
4. clear() clears the whole vector, not just the one at the index -> erase() is more likely
5. a find() function would be very useful - i.e search for a name ...
6. use push_back() and pop_back() <vector> functionality perhaps? Who cares what the index is? (Even though it's useful to avoid duplicates)
Thank you all for clearing my doubt and helping me out.
@againtry
Thank you for those points. I'd like to learn more about <map>. Is there any book or other resource you'd recommend me to refer to, so that I get a better idea.
Actually, the problem was for us to try out direct accessing and store the name of the person at the index = phone number. I wanted to try it out for a hypothetical case where all phone numbers were at max 2 digits long. At the end we concluded that this method isn't useful because real life numbers can be 10-12 digits long.
@viraamrao
For a good start on this and other "(STL) containers" you can't go past the tutorials and references on this site. They all come with short working sample code.