简体   繁体   English

字符串向量打印成int?

[英]string vector printed into int?

I'm currently doing an activity w/ vectors and I stumbled upon this question.我目前正在做一个带有向量的活动,我偶然发现了这个问题。

A procedure that takes an array variable of size 4 by 4. The array variable should be string type.一个接受大小为 4 x 4 的数组变量的过程。数组变量应该是字符串类型。 The contents of the array are illustrated below.数组的内容如下所示。

The contents:内容:

aa  ab  ac  ad
ba  bb  bc  bd
ca  cb  empty   cd
da  db  dc  dd

This is what your procedure should do, gets the board and displays to the user as below,这是您的程序应该做的,获取板并显示给用户,如下所示,

1   2   3   4
5   6   7   8
9   10  empty   12
13  14  15  16

I managed to print it out as strings but I have no idea on how to turn it into int after printing.我设法将其打印为字符串,但我不知道如何在打印后将其转换为 int。

#include <iostream> 
#include <vector> 
using namespace std; 

int main() 
{ 
    vector<vector<string> > thirdQuiz
    { 
        { "aa", "ab", "ac", "ad" }, 
        { "ba", "bb", "bc", "bd" }, 
        { "ca", "cb", "empty", "cd" },
        { "da", "db", "dc", "dd" },  
    };

    // Displaying the 2D vector   
    for (int i = 0; i < thirdQuiz.size(); i++) 
    { 
        for (int j = 0; j < thirdQuiz[i].size(); j++)
        {
            cout << thirdQuiz[i][j] << " "; 
        } 
        cout << endl; 
    } 
    return 0; 
} 

If I assume right, you need to display the index.如果我假设正确,您需要显示索引。 Then several possibilities come around.然后出现了几种可能性。
One is:一种是:

  1. Multiply the outer index with the inner size and add the inner counter:将外部索引与内部大小相乘并添加内部计数器:
    auto count = i * thirdQuiz[i].size() + j + 1; But be aware this only works if the inner vectors all have the same size.但请注意,这只适用于内部向量都具有相同大小的情况。
  2. Then you have to check if the value is empty then print "empty" or the number.然后你必须检查值是否为空,然后打印“空”或数字。
    for (int i = 0; i < thirdQuiz.size(); i++) { 
        for (int j = 0; j < thirdQuiz[i].size(); j++) {
            if(!thirdQuiz[i][j].empty() && thirdQuiz[i][j] != "empty"){
                std::cout << i * thirdQuiz[i].size() + j + 1 << " ";
                continue;
            }
            std::cout << "empty" << " "; 
        } 
        std::cout << endl; 
    } 

A more robust way would be to just count all entries in your vectors:更强大的方法是只计算向量中的所有条目:

    size_t count{};
    for (auto const& inner_vec: thirdQuiz) { 
        for (auto const& string_val: inner_vec) {
            ++count;
            if(!string_val.empty() && string_val != "empty"){
                std::cout << count << " ";
                continue;
            }
            std::cout << "empty" << " "; 
        } 
        std::cout << endl; 
    } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM