Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How Do I Print a Vector of Tuples?

Tags:

c++

tuples

vector

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

like image 835
Damonlaws Avatar asked Dec 04 '25 19:12

Damonlaws


1 Answers

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
like image 54
gsamaras Avatar answered Dec 07 '25 08:12

gsamaras



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!