簡體   English   中英

c++ - 如何在C++中從反向顯示向量的向量中的行的內容?

[英]How do I display the contents of a row in vector of vector from reverse in C++?

為了在 C++ 中顯示 vector 的 vector 的內容,我們使用嵌套的 for 循環。 像這樣的東西:

for (auto i = 0; i < x.size(); i++) {
        for (auto j = 0; j < x[i].size(); j++) 
            std :: cout << x[i][j] << " ";
        std :: cout << std :: endl;
    }

(這里 x 是向量的向量。)

但是說我想以相反的方式顯示一行的內容,並以常規方式顯示所有其他行。 我該怎么做? 我應該單獨反轉行並打印向量嗎? 或者有另一種方法嗎?

我不確定這是否是你想要的,但是。

這其中的任何一個 2

這將顛倒i的順序

for (int i = x.size() - 1; i >= 0; i--) {
        for (int j = 0; j < x[i].size(); j++){
            std :: cout << x[i][j] << " ";
        }
        std::cout << std::endl'
}

基本上,這里發生的事情是,我在向量的最后一個索引處開始了i ,以顛倒順序

或者

這將顛倒j的順序

for(int i = 0; i < x.size(); ++i){
        for(int j = x[1].size() - 1; j >= 0; --j){
            std::cout << x[i][j] << " ";
        }
        std::cout << std::endl;
}

在這里,我在向量的最后一個向量索引處開始了j

請注意,不要將 auto 用於for循環的初始化部分(在這種情況下),因為如果您執行auto i = x.size() - 1您將得到一個 unsigned long,並且會造成一些麻煩,因為這只有當值 <= -1 時循環才會停止。

(1, 2, 3, 4, 5) 和第二行我有: (21, 22, 23, 24, 25)。 我想以相反的方式顯示第一行的內容(例如:5、4、3、2、1)和以常規方式顯示第二行的內容(21、22、23、24、25)

如果這是你想要的,那么

bool notReverse = false;
    for(int i = 0; i < x.size(); ++i){
        int sIndex = notReverse ? 0 : x[0].size() - 1,   // starting index
            eIndex = notReverse ? x[0].size() : -1,      // last index
            mod_j  = notReverse ? 1 : -1;                // modifier
            
        for(int j = sIndex; j != eIndex; j+=mod_j){
            std::cout << x[i][j] << std::endl;
        }
        notReverse = true;
}

我創建了一些變量來決定值是否會反轉。

雖然您可以更改循環的方向,但如果更多指令在原始方向(i++)上工作,您應該只更改索引:

auto y=x;
for (auto i = 0; i < x.size(); i++) {
    for (auto j = 0; j < x[i].size(); j++){
        std :: cout << x[i][j] << " ";//comment 1            
        std :: cout << y[(x.size()-1)-i][j] << " ";//comment 2
    }
    std :: cout << std :: endl;
}

注釋 1:使用原始索引方向的命令 (0,1,2...)

注釋 2:使用“i”迭代器反向索引,從最后一個位置 (x.size()-1) 開始(“-1”,因為第一個元素的索引為零)。 請看一下這個:

normal indexing (i++):
0,1,2,3,4,5
reverse indexing:
5,4,3,2,1,0
size:5 elements
size - (each index in normal indexing):
5-0,5-1,5-2,5-3,5-4,5-5
  5,  4,  3,  2,  1,  0    -> reverse indexing 

處理兩種形式的索引很重要(在索引時更改順序並在循環元素時更改順序),我建議您也看看@Renz Aguirre 的答案。

暫無
暫無

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

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