Home > Backend Development > C++ > body text

How can I read graph adjacency information from a text file and store it into a vector in C ?

Mary-Kate Olsen
Release: 2024-10-31 06:01:01
Original
890 people have browsed it

How can I read graph adjacency information from a text file and store it into a vector in C  ?

Reading Graph Adjacency Information from a Text File in C

To read graph adjacency information from a text file and store it into a vector, where each line contains a variable number of integers, we can employ the following steps:

Firstly, we include necessary headers for file manipulation and string streams:

<code class="cpp">#include <fstream>
#include <sstream></code>
Copy after login

Next, we open the text file using an ifstream object:

<code class="cpp">std::ifstream infile("thefile.txt");</code>
Copy after login

We establish a string to store each line:

<code class="cpp">std::string line;</code>
Copy after login

Then, we enter a loop to read each line one by one:

<code class="cpp">while (std::getline(infile, line))</code>
Copy after login

For each line, we create an istringstream to process the string:

<code class="cpp">std::istringstream iss(line);</code>
Copy after login

We declare an integer n and a vector v to store the parsed integers:

<code class="cpp">int n;
std::vector<int> v;</code>
Copy after login

Inside another while loop, we iterate over the istringstream, reading integers into n and pushing them into the vector:

<code class="cpp">while (iss >> n)
{
    v.push_back(n);
}</code>
Copy after login

Finally, we can use the v vector to represent the adjacency information.

The above is the detailed content of How can I read graph adjacency information from a text file and store it into a vector in C ?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!