473,480 Members | 1,536 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

std::vector<struct> insertion question

131 New Member
Is it possible to assign function parameters directly into a vector holding a structure instead of declaring a local struct variable?

Below is sort of what I'm wanting to do; the following is declared as private data in a class

Expand|Select|Wrap|Line Numbers
  1. typedef struct
  2. {
  3.     std::string s1;
  4.     std::string s2;
  5.     int i1;
  6.     int i2;
  7. } item;
  8.  
  9. std::vector<item> *items;
  10.  
I've got a member function dataAddItem()

Expand|Select|Wrap|Line Numbers
  1. bool className::dataAddItem(
  2.    const std::string &s1,
  3.    const std::string &s2,
  4.    const int &i1,
  5.    const int &i2)
  6. {
  7.  
  8.    // items->push_back(struct) ??
  9. }
  10.  
I'm wanting to assign the parameters without having to declare a temporary structure. Is this possible?

TIA
Dec 22 '12 #1
6 11462
weaknessforcats
9,208 Recognized Expert Moderator Expert
No. Since you have a vector<item> you have to push_back and item.

However, once the item is in the vector then you can:

Expand|Select|Wrap|Line Numbers
  1. items[n].s1 = "hello";
This violates encapsulation but it will work.

Don't worry about temporary copies until your code works. Then you can go through it and use references where possible. After which you replace any remaining pointers with smart poiters. However, just using references will remove 90% of your pointers.

I am not sure why your items is a pointer vector<item>. Are you making assumptions abut how vector is implemented? I can guarantee it's not on the stack.
Dec 22 '12 #2
divideby0
131 New Member
Thank you for your reply.

I'm finding that things I'm somewhat familiar with in C go horribly wrong in C++.

I found a bit of code that *appears* to do what I'd like but I don't know if it's valid. My knowledge of C++ is solely based on snippits of code found in forums and whatnot.

Expand|Select|Wrap|Line Numbers
  1. struct item
  2. {
  3.    ...
  4.    item(const string &p1, const string &p2, ...) :
  5.       s1(p1), s2(p2), ... ) {}
  6.  
  7. }; // handy feature but bizzare compared to C
  8.  
Expand|Select|Wrap|Line Numbers
  1. bool ::dataAddItem(param list)
  2. {
  3.    items->push_back(item(param list));
  4.    // use a constructor within a struct?? weird
  5. }
this compiles and runs without errors, but is it valid?

With C, I was told it's better to use a pointer to a structure or large data, so I tried the same approach with the vector.
Dec 22 '12 #3
weaknessforcats
9,208 Recognized Expert Moderator Expert
Please forget C. C is the reason there is a C++.

C++ Secret: There are no classes in C++.

In C the only way you can have a data item with members is to use a struct. Therefore, in C++ you use a struct to encapsulate members since C++ extends C.

C++ uses constructors to initialize objects. Therefore, structs have constructors. Ditto for destructors. Member functions, etc...

If you define every member of a struct as public, private or protected, then there is no difference between a struct and a class.

C++ Secret #2: The "class" keyword is there to make object-oriented programmers think that C++ is object-oriented, but it's not really.

In the OOP world a class is a pattern for an object. So you say an object is an instance of a class. The OOP world never heard of a struct since it is C language artifact. By implementing a "class" as a struct, C++ bridges C to OOP. If you can use a struct you automatically can use a class.

Your example code just shows me a struct with a constructor.
Dec 22 '12 #4
divideby0
131 New Member
Once again, I cannot thank you enough taking the time to explain things.

Here's a compacted version of what I'm working with

Expand|Select|Wrap|Line Numbers
  1.  
  2. class test
  3. {
  4.    private : 
  5.  
  6.    struct item
  7.    {
  8.        string s1;
  9.        string s2; 
  10.        item(const string &init_data1,
  11.             const string &init_data2) : 
  12.             s1(init_data1), s2(init_data2) {}
  13.    };
  14.  
  15.    vector<item> items;
  16.    vector<item>::iterator it;
  17.  
  18.    public : bool dataAddItem(const string &);
  19.             void dataShowItems();
  20. };
  21.  
  22. bool test::dataAddItem(const string &param1,
  23.                        const string &param2)
  24. {
  25.    items.push_back( item(param1, param2) );
  26. }
  27.  
  28. void test::dataShowItems()
  29. {
  30.     for(it = items.begin(); it != items.end(); ++it)
  31.        cout << it->s1
  32.             << "\n"
  33.             << it->s2
  34.             << "\n\n";
  35. }
  36.  
  37. test obj;
  38. obj.dataAddItem("s1 data", "s2 data");
  39. obj.dataShowItems();
  40.  
  41. // output
  42. // s1 data
  43. // s2 data
  44.  
What I don't quite get with dataAddItem is how push_back is able to use item's constructor so that "s1 data" and "s2 data" are added to the vector.
Dec 23 '12 #5
weaknessforcats
9,208 Recognized Expert Moderator Expert
Here's the line of code:

Expand|Select|Wrap|Line Numbers
  1. items.push_back( item(param1, param2) );
So you are calling an item constructor as the argument to push_back. To make that call, the compiler creates an item object and calls the construtor on it. Now param1 and param2 are inside this hidden (temporary) item object. This temporary object is passed to push_back which adds a copy of it (copy constructor call) to the vector and finally as the temporary goes out of scope, the item destructor is called.

In C you would need to make all these calls yourself (if you remembered) but in C++ the compiler creates, initializes and cleans up the object withut bothering you. This drives C programmers nuts since they want total control of their program. None of this automatic protection stuff.
Dec 23 '12 #6
divideby0
131 New Member
Thank you; I appreciate your patience and your comments have been extremely helpful.
Dec 23 '12 #7

Sign in to post your reply or Sign up for a free account.

Similar topics

20
17735
by: Anonymous | last post by:
Is there a non-brute force method of doing this? transform() looked likely but had no predefined function object. std::vector<double> src; std::vector<int> dest; ...
3
1633
by: ali labed | last post by:
Does MS Visual C++ not accept vector of a structure ? (in acceptes vector<int>) struct str1 { string name; int num; }; vector<str1> vec_str( 10 ); // <== rejected
1
7271
by: sharmadeep1980 | last post by:
Hi All, I am facing a very unique problem while compling my project in "Release" build. The project is building in DEBUG mode but giving linking error on Release build. Here is the error:...
9
8876
by: aaragon | last post by:
I am trying to create a vector of type T and everything goes fine until I try to iterate over it. For some reason, the compiler gives me an error when I declare std::vector<T>::iterator iter;...
12
5678
by: arnuld | last post by:
in C++ Primer 4/3 Lippman says in chapter 3, section 3.3.1: vector<stringsvec(10); // 10 elements, each an empty string here is the the code output & output from my Debian box running "gcc...
8
5347
by: Lionel B | last post by:
On my platform I find that the std::vector<boolspecialisation incurs a significant performance hit in some circumstances (when compared, say, to std::vector<intprogrammed analagously). Is it...
4
3337
by: stinos | last post by:
Hi All! suppose a class having a function for outputting data somehow, class X { template< class tType > void Output( const tType& arg ) { //default ToString handles integers/doubles
8
3951
by: barcaroller | last post by:
I have a pointer to a memory block. Is there a way I can map a vector<Tto this memory block? I would like to take advantage of the powerful vector<T> member functions. Please note that I cannot...
2
5580
by: Rockair | last post by:
hi! there is a class: class card { static vector<string> names; //... };
8
3584
by: jacek.dziedzic | last post by:
Hi! I need to be able to track memory usage in a medium-sized application I'm developing. The only significant (memory-wise) non- local objects are of two types -- std::vector<and of a custom...
0
7044
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
7045
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6741
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
6944
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4782
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4483
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
2995
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
2985
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
563
muto222
php
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.