string help

Sep 11, 2013 at 12:36pm
Hi. I am a bit confused.

If I have a class called Name for instance;
1
2
3
4
5
6
7
8
9
  class Name
{
private:
string *name;
int num;

public:

Name(string n);


is it possible to create an array of 3 Name objects.

I tried Name *n = new Name[];
this doesnt work.

Please help
Sep 11, 2013 at 12:44pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <string>
#include <vector>


class Name
{
private:
	std::string m_name;
	int m_num;

public:
	Name(std::string n)
	{
		m_name = n;
	}
};

int main()
{
	std::vector<Name> namesCollection;

	namesCollection.push_back(Name("tom"));
	namesCollection.push_back(Name("dick"));
	namesCollection.push_back(Name("harry"));

	return 0;
}


or use an array of Name*'s if you wanna dynamically create and add to the collection on the fly.
Sep 11, 2013 at 12:47pm
thanks but Is there a way to recieve just the first elements of every object;

1
2
3
4
5

	namesCollection.push_back(Name("tom the guy"));
	namesCollection.push_back(Name("dick the dick"));
	namesCollection.push_back(Name("harry the potter"))


To retrieve tom dick and harry only
Sep 11, 2013 at 1:22pm
can you explain a bit more please?
Sep 11, 2013 at 1:28pm
namesCollection[0] or namesCollection.at(0)?
Sorry, I read through your question too fast and gave an answer that doesn't help you very much. Look at TheIdeasMan's post instead.
Last edited on Sep 11, 2013 at 2:40pm
Sep 11, 2013 at 2:09pm
BUT IT GIVES ME THE MEMORY ADDRESS.ANY SUGGESTIONS
Sep 11, 2013 at 2:31pm
Hi ngopza,

Have a look at these:

http://www.cplusplus.com/reference/string/string/find/
http://www.cplusplus.com/reference/string/string/find_first_of/


With the second one, you could use this to search for spaces, so you can find the first word, regardless of what that word is.

Hope all goes well.
Last edited on Sep 11, 2013 at 2:32pm
Topic archived. No new replies allowed.