Can't figure out why this code won't work

I'm doing an exercise in a textbook. All I have to do is print and label 3 vectors. I have no idea why it wont work

EDIT: Nevermind, I just realized that I tried to straight up print the vector. The best way to print the values would be with a for loop correct?
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
#include <iostream>
#include <vector>
#include <string>

void print(std::string& label, std::vector<double>& v);

int main()
{
    std::vector<double> v1 = {6,7,8,9,10};
    std::vector<double> v2 = {1,2,3,4,5};
    std::vector<double> v3 = {11,12,13,14,15};

    std::string label_v1 = "v1";
    std::string label_v2 = "v2";
    std::string label_v3 = "v3";

    print(label_v1, v1);
    print(label_v2, v2);
    print(label_v3, v3);

    return 0;

}

void print(const std::string& label, const std::vector<double>& v)
{
   std::cout << label << " = " << v << std::endl;
}
Last edited on
print prototype:
void print(std::string& label, std::vector<double>& v);

print definition:
void print(const std::string& label, const std::vector<double>& v)

Something about them does not match up.
Oh yeah you're right. Here's what I got now, would this be the most efficient way of printing the values of the vector?


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
31
32
33
34
35
36
37
38
39
40
41
42
43
#include <iostream>
#include <vector>
#include <string>


void print(const std::string& label, const std::vector<double>& v);

int main()
{
    std::vector<double> v1 = {6,7,8,9,10};
    std::vector<double> v2 = {1,2,3,4,5};
    std::vector<double> v3 = {11,12,13,14,15};

    std::string label_v1 = "v1";
    std::string label_v2 = "v2";
    std::string label_v3 = "v3";

    print(label_v1, v1);
    print(label_v2, v2);
    print(label_v3, v3);

    return 0;

}

void print(const std::string& label, const std::vector<double>& v)
{
    for(int i = 0; i<v.size(); i++)
    {
        if (i == 0)
        {
            std::cout << label << " = " << v[i] << ", ";
        }

        else
        {
            std::cout << v[i] << ", ";
        }
    }

    std::cout << "\n\n";

}
>would this be the most efficient way of printing the values of the vector?

In your print function you check for the first element of v each iteration. Why not move that outside of the loop and only check once?
1
2
3
4
5
6
7
8
9
10
11
void print(const std::string& label, const std::vector<double>& v) {
    if(0 < v.size())
        std::cout << label << " = " << v[0] << ", ";
 
    for(size_t i = 1; i < v.size(); i++)
        std::cout << v[i] << ", ";

    std::cout << "\n\n";

return;
}


Also, since you are using vectors it would be better to use an iterator instead of the [] operator, as they are much more optimized for sequential access.
Last edited on
Topic archived. No new replies allowed.