Vectors and Structs

Making a vector of structs

Page 1 of 1

11 Replies - 2063 Views - Last Post: 25 November 2009 - 07:49 AM Rate Topic: -----

#1 UofMCreed   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 04-October 08

Vectors and Structs

Post icon  Posted 24 November 2009 - 12:12 PM

Hello, im making a program that requires a vector of structs but I cant seem to get it going properly. Ive tried to google the problem i am having but i cant seem to get a straight forward answer to my problem. I have declared a vector of structs, i understnd that, but my problem is putting a new struct into the vector and place data inside of the struct. Below is some basic code for the problem I am having. I get only one error message when i try and compile. Can someone show me what i am doing wrong? Its prolly something basic that i am overlooking, any help would be appreciated! Thnx.

#include<iostream>
#include<string>
#include<vector>

using namespace std;

struct Node
{
	string name;
	int age;
};


int main()
{
vector<Node> Vec;
string Name = "Mike";

Vec.push_back( Node(Name, 21) ); //MY problem is here, im not even sure im doing this part correcttly

return 0;
}



Is This A Good Question/Topic? 0
  • +

Replies To: Vectors and Structs

#2 xtreampb   User is offline

  • D.I.C Regular

Reputation: 15
  • View blog
  • Posts: 345
  • Joined: 20-June 07

Re: Vectors and Structs

Posted 24 November 2009 - 12:33 PM

first off if you are going to initialize a structor with data you need to make a constructor that supports that

struct Node(string N, int A)
{
string Name=N;
int Age=A;
};



then you can do something like this

vector<node> NodeVec;
string name="mike";

node *MyNode=new node(Name, 21);
//MyNode is a pointer, I use them as much as possible

NodeVec.push_back(&MyNode);

delete MyNode;



This post has been edited by xtreampb: 24 November 2009 - 12:34 PM

Was This Post Helpful? 0
  • +
  • -

#3 Bench   User is offline

  • D.I.C Lover
  • member icon

Reputation: 945
  • View blog
  • Posts: 2,464
  • Joined: 20-August 07

Re: Vectors and Structs

Posted 24 November 2009 - 03:01 PM

View Postxtreampb, on 24 Nov, 2009 - 07:33 PM, said:

first off if you are going to initialize a structor with data you need to make a constructor that supports that

struct Node(string N, int A)
{
string Name=N;
int Age=A;
};


You're right that the OP needs a constructor, but way off the mark with the struct example- Please don't post code in reply to help threads where you've just taken a wild stab-in-the-dark, and not checked your solution with a compiler first. here's one which will compile
struct Node
{
    string name;
    int age;
    Node(string n, int a) : name(n), age(a) {}
}; 



View Postxtreampb, on 24 Nov, 2009 - 07:33 PM, said:

then you can do something like this
vector<node> NodeVec;
string name="mike";

node *MyNode=new node(Name, 21);
//MyNode is a pointer, I use them as much as possible

Yuck! That's a terrible habit, and in this case its wholly unnecessary since the form which the OP had used of Vec.push_back( Node(Name,21) ); worked just fine.

Pointers in C++ are evil and should be used as rarely as possible (You could have at least used an auto_ptr to avoid having to use 'delete'). There are many tools in the STL which make it easy to avoid using pointers for alot of problems - I strongly suggest you research the STL in more depth and properly understand how to use it to write better, safer, cleaner code.

With the constructor in place, the OP's original main function will work just fine
#include <string>
#include <vector>
using namespace std;

struct Node
{
    string name;
    int age;
    Node(string n, int a) : name(n), age(a) {}
};

int main()
{
    vector<Node> Vec;
    string Name = "Mike";

    Vec.push_back( Node(Name, 21) );

    return 0;
} 

This post has been edited by Bench: 24 November 2009 - 03:09 PM

Was This Post Helpful? 0
  • +
  • -

#4 UofMCreed   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 04-October 08

Re: Vectors and Structs

Posted 24 November 2009 - 03:55 PM

Hey Thanks for the help, i was wondering though, I dont understand the line of code you added at the end of my struct. What does that do???

View PostBench, on 24 Nov, 2009 - 02:01 PM, said:

View Postxtreampb, on 24 Nov, 2009 - 07:33 PM, said:

first off if you are going to initialize a structor with data you need to make a constructor that supports that

struct Node(string N, int A)
{
string Name=N;
int Age=A;
};


You're right that the OP needs a constructor, but way off the mark with the struct example- Please don't post code in reply to help threads where you've just taken a wild stab-in-the-dark, and not checked your solution with a compiler first. here's one which will compile
struct Node
{
    string name;
    int age;
    Node(string n, int a) : name(n), age(a) {}
}; 



View Postxtreampb, on 24 Nov, 2009 - 07:33 PM, said:

then you can do something like this
vector<node> NodeVec;
string name="mike";

node *MyNode=new node(Name, 21);
//MyNode is a pointer, I use them as much as possible

Yuck! That's a terrible habit, and in this case its wholly unnecessary since the form which the OP had used of Vec.push_back( Node(Name,21) ); worked just fine.

Pointers in C++ are evil and should be used as rarely as possible (You could have at least used an auto_ptr to avoid having to use 'delete'). There are many tools in the STL which make it easy to avoid using pointers for alot of problems - I strongly suggest you research the STL in more depth and properly understand how to use it to write better, safer, cleaner code.

With the constructor in place, the OP's original main function will work just fine
#include <string>
#include <vector>
using namespace std;

struct Node
{
    string name;
    int age;
    Node(string n, int a) : name(n), age(a) {}
};

int main()
{
    vector<Node> Vec;
    string Name = "Mike";

    Vec.push_back( Node(Name, 21) );

    return 0;
} 

Was This Post Helpful? 0
  • +
  • -

#5 EdwinNameless   User is offline

  • D.I.C Addict
  • member icon

Reputation: 128
  • View blog
  • Posts: 723
  • Joined: 15-October 09

Re: Vectors and Structs

Posted 24 November 2009 - 04:05 PM

View PostUofMCreed, on 24 Nov, 2009 - 02:55 PM, said:

Hey Thanks for the help, i was wondering though, I dont understand the line of code you added at the end of my struct. What does that do???


It initializes your struct values.
Was This Post Helpful? 0
  • +
  • -

#6 Bench   User is offline

  • D.I.C Lover
  • member icon

Reputation: 945
  • View blog
  • Posts: 2,464
  • Joined: 20-August 07

Re: Vectors and Structs

Posted 24 November 2009 - 04:33 PM

the syntax I used in my first reply is known as an initialiser list - its used before the beginning of a constructor body for initialising data in a class. If you don't like that, then another way to write a solution to this problem is to use the body of the constructor like this
struct Node
{
    string name;
    int age;
    Node(string n, int a)
    {
        name = n;
        age = a;
    }
}; 
Initialiser lists aren't actually needed here, although in many situations they're preferred over using the constructor body - and occasionally even necessary.
Was This Post Helpful? 0
  • +
  • -

#7 UofMCreed   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 37
  • Joined: 04-October 08

Re: Vectors and Structs

Posted 24 November 2009 - 06:38 PM


Hey guys thnk for all the help. I do have one more problem though. When i try and pass the vector to a function i get an error. The error is in the line of code where the function is called in main. I attached my code below, do i need to use pointers or something? Appreciate help. Thanks


ERROR MESSAGE:
error C2664: 'Print' : cannot convert parameter 1 from 'std::vector<_Ty>' to 'Node &'


#include<iostream>
#include<string>
#include<vector>

using namespace std;

struct Node
{
	string name;
	int age;
	Node(string n, int a) : name(n), age(a) {}
};

void Print(Node & Vec)
{

}


int main()
{
vector<Node> Vec;
string Name = "Mike";

Vec.push_back( Node(Name, 21) );

Print(Vec);//MY ERROR OCCURS HERE, AND I DO NOT KNOW WHY

return 0;
}


Was This Post Helpful? 0
  • +
  • -

#8 xtreampb   User is offline

  • D.I.C Regular

Reputation: 15
  • View blog
  • Posts: 345
  • Joined: 20-June 07

Re: Vectors and Structs

Posted 24 November 2009 - 10:01 PM

void Print(node &Vec)
that is saying that Vec is a node. I assume that you want to pass your vector of nodes, so try this
void Print(vector<Node> &Vec)

I'm sorry that you have a different programming style than I do, but I use pointers as much as possible due to the fact that i am working with raw memory address and that gives me as much control over my vars as possible. With pointers, i can arrange ALL of the memory that I am going to use with my code. Yes the STL is powerful but most of it is wasted and unappriciated if you don't know how to do what the STL does yourself. I write software for robots as well as business applications. Memory management is a top priority to me and pointers gives me as much control as possible. Now with all this power and control you have to be disciplined enough to take count of all the memory that you are using (especially for multithreading) so that memory leaks don't become a problem.

I am just curious, why do you think pointers are evil? Do you also think that 'goto' is bad

This post has been edited by xtreampb: 24 November 2009 - 10:11 PM

Was This Post Helpful? 0
  • +
  • -

#9 Bench   User is offline

  • D.I.C Lover
  • member icon

Reputation: 945
  • View blog
  • Posts: 2,464
  • Joined: 20-August 07

Re: Vectors and Structs

Posted 25 November 2009 - 03:53 AM

View Postxtreampb, on 25 Nov, 2009 - 05:01 AM, said:

void Print(node &Vec)
that is saying that Vec is a node. I assume that you want to pass your vector of nodes, so try this
void Print(vector<Node> &Vec)

I'm sorry that you have a different programming style than I do, but I use pointers as much as possible due to the fact that i am working with raw memory address and that gives me as much control over my vars as possible. With pointers, i can arrange ALL of the memory that I am going to use with my code. Yes the STL is powerful but most of it is wasted and unappriciated if you don't know how to do what the STL does yourself. I write software for robots as well as business applications. Memory management is a top priority to me and pointers gives me as much control as possible. Now with all this power and control you have to be disciplined enough to take count of all the memory that you are using (especially for multithreading) so that memory leaks don't become a problem.

I am just curious, why do you think pointers are evil? Do you also think that 'goto' is bad
Just to be clear, don't think 'goto' is bad per-se, but i do think its evil in C++. To me, 'bad' suggests something is wrong with a program; whereas 'evil' is language-specific (i.e something which is "evil" in C++ may be perfectly OK in C or ASM). Its also more to do with a strong likelyhood that a programmer will fall foul of some "gotcha", or maybe just end up writing something which is ugly and difficult to maintain. (Particularly if the programmer doesn't fully understand the implications of what they're doing)

This isn't about style but more to do with context. You say that you need fine control over memory for the kind of applications you write - that's fine, and a very valid reason for using pointers and other explicit memory management techniques in your own work, although I think most problems you'll see on this forum are very different.

The real issue I have is with "evil" constructs in a language learning community (and in some beginner books/tutorials) is that they are too often used unnecessarily to illustrate solutions to beginner problems in situations where easier, safer and more idiomatic options are available - shifting focus away from high-level problem solving and down towards nitpicky language issues, and in turn encouraging bad habits of using C++ as "a better C".
Since beginner programmers are still in the habit-forming stage of learning, I believe overloading learners with low-level issues can really detract from the big picture of problem solving, whilst they may be blissfully unaware of better ways to use the language.

Every language has its evils - pointers aren't alone in my list of C++ evils; I'd also include arrays, unions, goto, #define macros, placement new (and possibly others if I thought about it).
Usually these raise alarm bells if I see them used in any production code I'm working with (I am involved in writing financial applications, so fine control over memory is rarely a top priority for me personally). In fairness, parts of the system I work with are over 30 years old, and I am often finding myself re-writing chunks of poorly maintained legacy C/C++ code where "clever" (read: ugly) hacks involving some of those evils have been used to ill effect for anyone maintaining the system. But sometimes new programmers to join my team are worryingly naive about C++, and end up writing poor code from scratch - for which I generally feel that books and instructors have let those programmers down in their learning.
Was This Post Helpful? 0
  • +
  • -

#10 baavgai   User is offline

  • Dreaming Coder
  • member icon


Reputation: 7249
  • View blog
  • Posts: 15,120
  • Joined: 16-October 07

Re: Vectors and Structs

Posted 25 November 2009 - 04:43 AM

View Postxtreampb, on 24 Nov, 2009 - 11:01 PM, said:

I am just curious, why do you think pointers are evil? Do you also think that 'goto' is bad


I'm curious, why C++ and not C. Without taking advantage of higher level abstractions and an emphasis on embedded systems and memory management, C++ seems a waste. The biggest problem / advantage of C++ is that objects can hide all the mess. In a limited memory space, this is rarely desirable.

For C++ and pointers... perhaps not evil, but to be avoided. I find myself falling back to them, sometimes. I believe if you forced a beginner to live without them they'd probably be a better C++ programmer. ( Albeit a useless C programmer. )
Was This Post Helpful? 0
  • +
  • -

#11 Bench   User is offline

  • D.I.C Lover
  • member icon

Reputation: 945
  • View blog
  • Posts: 2,464
  • Joined: 20-August 07

Re: Vectors and Structs

Posted 25 November 2009 - 06:58 AM

View Postbaavgai, on 25 Nov, 2009 - 11:43 AM, said:

For C++ and pointers... perhaps not evil, but to be avoided. I find myself falling back to them, sometimes. I believe if you forced a beginner to live without them they'd probably be a better C++ programmer. ( Albeit a useless C programmer. )

I've taken a similar approach with programmers who I mentor through the systems I work with - refusing to sign-off work which uses raw arrays is a sure way to grab their attention in the first few weeks of a new job - I believe doing this has had its successes, and most work which falls on my desk for peer review thereafter shows a few hard lessons learned.
My copy of Accelerated C++ stays with me at work, and I'm a true believer in the approach that the authors use - arrays and pointers tucked away towards the later chapters of the book, yet vectors, iterators and algorithms all appear in the early/mid chapters

With that said, Most of my success comes with interns and graduates (who are usually more familiar with other OO languages) - Java programmers often dislike pointers, and welcome the opportunity to see the similarities between the STL and Java's generic collections classes. Of course sometimes you just can't teach an old dog new tricks that easily - I've met seasoned C programmers who are resistant to this kind of approach if they see it as unnecessary or even patronised by the idea that the STL could be better than something they've written.
Was This Post Helpful? 0
  • +
  • -

#12 EdwinNameless   User is offline

  • D.I.C Addict
  • member icon

Reputation: 128
  • View blog
  • Posts: 723
  • Joined: 15-October 09

Re: Vectors and Structs

Posted 25 November 2009 - 07:49 AM

View PostBench, on 25 Nov, 2009 - 05:58 AM, said:

Java programmers often dislike pointers, and welcome the opportunity to see the similarities between the STL and Java's generic collections classes.


I second that, I'm experiencing it first hand. I have been developing in Java for the past 12 years, and started learning C++ 3 months ago, but the hardest for me is handling pointers, understanding the whole reference vs. copy bit and memory management. Simply because I didn't have to worry about these things before, I guess. I do find myself trying to draw parallels between the STL and the Java libraries, and I'm often surprised that certain things I was taking for granted must be done again in C++. In that respect, discovering Boost was a bit of an epiphany.

As I said somewhere else, starting with C++ after years of Java is like handling a chainsaw after years of playing with a Swiss knife, but the experience is worth it.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1