簡體   English   中英

我們可以從反向的 std::string 創建 std::istringstream object

[英]Can we create std::istringstream object from a reversed std::string

我正在使用推薦的 C++ 書籍學習 C++。 特別是,我閱讀了std::istringstream並看到了以下示例:

std::string s("some string");
std::istringstream ss(s);
std::string word;
while(ss >> word)
{
    std::cout<<word <<" ";
}

實際Output

some string

所需 Output

string some

我的問題是,我們如何使用反轉字符串(包含所需輸出中顯示的相反順序的單詞)來創建上面的std::istringstream object ss 我查看了std::istringstream 的構造函數,但找不到一個采用迭代器的構造函數,以便我可以傳遞str.back()str.begin()而不是傳遞std::string

如果使用臨時字符串,則可以將迭代器間接傳遞給istringstream構造函數:

#include <sstream>
#include <iostream>

int main()
{
    std::string s{"Hello World\n"};
    std::istringstream ss({s.rbegin(),s.rend()});
    std::string word;
    while(ss >> word)
    {
        std::cout<<word <<" ";
    }
}

Output :

dlroW olleH 

盡管那是反轉字符串,而不是單詞。 如果你想以相反的順序打印單詞,單獨的istringstream沒有多大幫助。 您可以使用一些容器來存儲提取的單詞,然后將它們反向打印:

#include <sstream>
#include <iostream>
#include <vector>

int main()
{
    std::string s{"Hello World\n"};
    std::istringstream ss(s);
    std::string word;
    std::vector<std::string> words;
    while(ss >> word)
    {
        words.push_back(word);
    }
    for (auto it = words.rbegin(); it != words.rend(); ++it) std::cout << *it << " ";
}

Output :

World Hello 

由於您添加了c++20標簽:

#include <sstream>
#include <string>
#include <iostream>
#include <vector>
#include <ranges>


int main()
{
    std::vector<std::string> vec;
    std::string s("some string");
    std::string word;
    std::istringstream ss(s);

    while(ss >> word)
    {
        vec.push_back(word);
    }

    for (auto v : vec | std::views::reverse)
    {
        std::cout << v << ' ';
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM