Damonlaws
Damonlaws

Reputation: 59

How Do I Print a Vector of Tuples?

So I'm trying to make a vector that contains tuples containing two ints, and I'm acquiring the ints from a text file source. To make sure I have the vector I want, I'm trying the print out my contents, but the output is not showing me anything. I'm not sure if it's because of my code, and where I put my text file. I'm just stuck at this point. If anything could help me with this, I'd appreciate it very much. Thanks

using namespace std;


int main()
{
ifstream file("source.txt");
typedef vector<tuple<int, int>> streets;
streets t; 
int a, b;

if (file.is_open()) 
{
    while (((file >> a).ignore() >> b).ignore())
    {
        t.push_back(tuple<int, int>(a, b));
        for (streets::const_iterator i = t.begin();i != t.end();++i)
        {
            cout << get<0>(*i) << endl;
            cout << get<1>(*i) << endl;
        }
        cout << get<0>(t[0]) << endl;
        cout << get<1>(t[1]) << endl;                   
    }
}

file.close();

system("pause");
return 0;

Here's my text file and where I placed it enter image description here

Here's my output from debugging, if that's important

Upvotes: 3

Views: 3277

Answers (1)

gsamaras
gsamaras

Reputation: 73444

You should use a loop, that will print one tuple at a time.

Complete minimal example:

#include <iostream>
#include <tuple>
#include <vector>
#include <fstream>
using namespace std;

int main(void) {
    std::ifstream infile("source.txt");
    vector<tuple<int, int>> streets;
    int a, b;
    while (infile >> a >> b)
    {
        streets.push_back(tuple<int, int>(a, b));
    }
    infile.close();
    for(auto& tuple: streets) {
        cout << get<0>(tuple) << " " << get<1>(tuple) << endl;   
    }
    return 0;
}

Output:

1 2
3 4
5 6
7 8

Upvotes: 1

Related Questions