2d string and int array

Nov 27, 2009 at 3:32am
Hi, I just started an assignment, and of course, new to c++, please forgive my ignorance.

I'm trying to create a 2d array, one column stores, a word(string) and the other column stores the word count(int)..

I'm supposed to use classes, and perhaps structs.. i just don't know how to do this..

How can I declare this? I am at a loss, here.

thanks in advance.
Last edited on Nov 27, 2009 at 3:41am
Nov 27, 2009 at 4:23am
You can't create two mixed datatypes in an array so you couldn't have the first be a string and second dimension be an int so yes you would want to use a class or struct. I would probably use struct since it defaults to public. Be sure to have the string header included when you do this with #include <string>. I would do something probably like the following below though:

struct characteristics {
string word;
int counter;
};

Then you can create datatypes of that struct so it'd look like characteristics my_variable; for example. Let me know if this helped.

Mike
Nov 27, 2009 at 6:42am
thanks for your quick reply, Mike,

can I put the struct, you created into a Class Word?

1
2
3
4
5
6
7
8
9
10
11
12
13
class Word
{
	public:
		void setup();
		void get();
		void set();
    private:
		struct characteristics
		{
			string word;
			int counter;
		};
};


If so.. how can I create new objects in the struct?
Word.characteristics word1; // is this how I create a new word item?

And also, how can I access word1?
cout << word1.word; // i.e. is this how I can access the word?

Overall, sorry - I keep reading the books and notes, but I can't seem to identify what I need to do.. :(
Nov 27, 2009 at 10:44am
If you are declaring it inside Word, you can use characteristics word1,
Outside Word, Word::characteristics word1
Nov 27, 2009 at 9:20pm
I'm a little out of practice personally with advanced concepts in object-oriented programming, especially when you have classes or structs nested within each other but I do know that a good resource that explains the details of that is Bruce Eckel's first volume of Thinking in C++ Second Edition which is free. Just Google it and you should find it for downloading or viewing online.

Mike
Nov 30, 2009 at 2:09am
Hay Bazzy, that makes perfect sense.. thanks!
and thanks Mike for the reference, I'll check it out.
I think that would work, but I think - I can just do it inside the class without the struct..
1
2
3
4
5
6
7
8
9
10
11
12
13
class Word
    {
        public:
            void setup(string);
            int getCount();
            string getWord(); 
            void setWord(string);
	    void setCount(int);
	private:
            string word;
	    int wordCount;
       
} word[500];
Topic archived. No new replies allowed.