Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 迭代文本对的最佳方法_C++_C++14 - Fatal编程技术网

C++ 迭代文本对的最佳方法

C++ 迭代文本对的最佳方法,c++,c++14,C++,C++14,这是可行的,但相当冗长: for (auto entry : std::vector<std::pair<int, char>> { {1, 'a'}, {2, 'b'}, {3, 'c'} } ) { int num = entry.first; char value = entry.second; ... } for(自动输入:std::vector{{{1,'a'},{2,'b'},{3,'c'}){ int num=entry.firs

这是可行的,但相当冗长:

for (auto entry : std::vector<std::pair<int, char>>  { {1, 'a'}, {2, 'b'}, {3, 'c'} } ) {
    int num = entry.first;
    char value = entry.second;
    ...
}
for(自动输入:std::vector{{{1,'a'},{2,'b'},{3,'c'}){
int num=entry.first;
char值=entry.second;
...
}

在C++11及更高版本中,必须有一种更优雅的方式…

您可以利用来构造对列表:

using std::make_pair;

for (auto x : {make_pair(1, 'a'), make_pair(2, 'b'), make_pair(3, 'c')})
{
    std::printf("%d %c", x.first, x.second);
}
在C++17中,可以使用并使其更加优雅:

using std::pair;

for (auto [a, b] : {pair(1, 'a'), pair(2, 'b'), pair(3, 'c')})
{
    std::printf("%d %c", a, b);
}

为什么一定要有?迭代一个已知类型的容器比迭代一个文字序列要常见得多。这已经比我们几年前编写的相同的东西要优雅得多。在C++ 17中应该是:<代码>(Auto[num,Value]):…的可能重复也没有多大帮助。我可以将
std::vector
更改为
std::map
,这会缩短一些。如果有办法避免第一件事/第二件事,在不使用两行的情况下为它们指定有意义的名称,那就太好了,但我现在使用的是C++14。