The right approach. struct?

So lets say I wanted to have 100+ variables preassigned. So that when we want to call it we can just do something like item.value;

Below would work but would it be the right approach or is there a better way of doing this tasks.

I thought I could make a class but I thought that would be over kill. so would having multiple lines of std::string word = "something";

Just looking for what would be best practice.



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
  #include <iostream>



struct words {
    std::string word1;
    std::string word2;
};




int main(int argc, const char * argv[]) {
    
    words myWord {
        "C++",
        "Is Fun"
    };
    
    
    std::cout << myWord.word1 << myWord.word2;
    
    
    return 0;
}
I don't know what "preassigned" means, but if you're dealing with a collection of objects it is often helpful to put them in a container.

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
28
29
30
// http://ideone.com/9a6RxY

#include <iostream>
#include <iterator>
#include <sstream>
#include <string>
#include <vector>

std::istringstream iss(
R"('Twas brillig, and the slithy toves
Did gyre and gimble in the wabe;
All mimsy were the borogoves,
And the mome raths outgrabe.

"Beware the Jabberwock, my son!
The jaws that bite, the claws that catch!
Beware the Jubjub bird, and shun
The frumious Bandersnatch!"
)");


using namespace std;

int main() {
    std::vector<std::string> words((std::istream_iterator<std::string>(iss)), 
                                       std::istream_iterator<std::string>());
	                               
    for (auto & word : words)
        std::cout << word << '\n';
}
The same thing you did can be accomplished through classes and it won't be any different than this just that the data will be encapsulate. And only certain member functions of that class can modify the data. It depends entirely on your use. But preferred method is by classes.
Stalker wrote:
The same thing you did can be accomplished through classes and it won't be any different than this just that the data will be encapsulate. And only certain member functions of that class can modify the data. It depends entirely on your use. But preferred method is by classes.


Maybe you meant a container of (class) objects? I wouldn't like a class with 100 members :+|

@enniferLostTheWar

If you use a std::vector you can refer to individual items with the subscript operator :

std::cout << "Item 10 is " << words[10-1] << "\n"; // subscripts start at 0

That example was very contrived, is is more flexible to use a variable in the subscript.

http://www.cplusplus.com/reference/vector/vector/
Yes that is what I meant or an array even
Topic archived. No new replies allowed.