C++:从管道填充向量

C++:从管道填充向量,c++,stl,C++,Stl,我想从命令行填充向量: more my.txt | myexe.x > result.txt 在C++中打开管道的最佳方法是什么? 谢谢 Arman。您的shell将把more的标准输出连接到myexe.x的标准输入。因此,您可以只读取std::cin,而不必担心输入是来自键盘还是其他程序 例如: vector<float> myVec; copy(istream_iterator<float>(cin), istream_iterator<float>

我想从命令行填充向量:

more my.txt | myexe.x > result.txt
在C++中打开管道的最佳方法是什么? 谢谢
Arman。

您的shell将把more的标准输出连接到myexe.x的标准输入。因此,您可以只读取std::cin,而不必担心输入是来自键盘还是其他程序

例如:

vector<float> myVec;
copy(istream_iterator<float>(cin), istream_iterator<float>(),
     back_inserter(myVec));

shell将把more的标准输出连接到myexe.x的标准输入。因此,您可以只读取std::cin,而不必担心输入是来自键盘还是其他程序

例如:

vector<float> myVec;
copy(istream_iterator<float>(cin), istream_iterator<float>(),
     back_inserter(myVec));

该特定管道连接到应用程序的stdin,因此您可以从那里读取。

该特定管道连接到应用程序的stdin,因此您可以从那里读取。

您可以使用std::copy from执行此操作,但不需要额外的依赖项

#include<iterator>

// ...
std::vector<float> them_numbers(std::istream_iterator<float>(std::cin),
                                std::istream_iterator<float>());
如果您事先确切知道您期望的值,则可以避免重新分配:

std::vector<float>::size_type all_of_them /* = ... */;
std::vector<float> them_numbers(all_of_them);
them_numbers.assign(std::istream_iterator<float>(std::cin),
                    std::istream_iterator<float>());
您可以使用std::copy from实现这一点,但不需要额外的依赖关系

#include<iterator>

// ...
std::vector<float> them_numbers(std::istream_iterator<float>(std::cin),
                                std::istream_iterator<float>());
如果您事先确切知道您期望的值,则可以避免重新分配:

std::vector<float>::size_type all_of_them /* = ... */;
std::vector<float> them_numbers(all_of_them);
them_numbers.assign(std::istream_iterator<float>(std::cin),
                    std::istream_iterator<float>());

谢谢Tomas,但输入的末尾呢?我应该在EOF结束时登记吗?还是什么?谢谢Tomas,但输入的结尾呢?我应该在EOF结束时登记吗?还是怎样