【问题标题】:How do I print the elements in vector that correspond to another array?如何打印向量中与另一个数组相对应的元素?
【发布时间】:2021-12-18 06:10:07
【问题描述】:

假设我有这个代码:

struct info{
    int num;
    int position;
    vector<int> vDigits;
    vector<string> vCode;

}
int main(){

    info info[2];    //
    info[0].num = 1234;
    info[1].num = 5678;

    //I do some calculations and call some functions for info[0]. What the functions
    do is they split every digit in '1234' and store them in vDigits and store position
    as 0(since its the first input) and a unique string is assigned to each digit and 
    stored vCode.
    // Same functions are applied to info[1] and position is stored as 1



}

我的问题是如何根据位置打印数字及其代码?不使用任何数据结构

我要打印:

pos: 0, digit: 1, code: "one"
pos: 0, digit: 2, code: "two"
pos: 0, digit: 3, code: "three"
pos: 0, digit: 4, code: "four"
pos: 1, digit: 5, code: "five"
pos: 1, digit: 6, code: "six"
pos: 1, digit: 7, code: "seven"
pos: 1, digit: 8, code: "eight"

【问题讨论】:

  • 为什么“不使用任何数据结构”?您是否将std::vector&lt;std::pair&lt;int, std::string&gt;&gt; 视为数据结构?你从哪里得到codes?
  • 您要解决的问题是什么?只是如您所显示的打印数据?您是否需要在结构中存储所有这些信息?
  • 不使用任何数据结构 -- 即使是数组也是一种数据结构,因此如果没有某种数据结构,您基本上无法编写任何有意义的程序。总之,“不使用任何数据结构”是很模糊的“要求”。

标签: c++ vector


【解决方案1】:

重载&lt;&lt; 运算符

std::ostream &operator<<(std::ostream &os, info const &inf) {
    for (int i = 0; i< inf.vDigits.size(); i++) {
        os << "pos: " << inf.position << ", digit: " << inf.vDigits[i] << ", code: " << '"' << inf.vCode[i] << '"';
    return os;
}

那么就:

std::cout << info[0] << info[1] << std::endl;

【讨论】:

    猜你喜欢
    • 2017-11-19
    • 2018-06-26
    • 1970-01-01
    • 2019-09-25
    • 1970-01-01
    • 1970-01-01
    • 2016-09-23
    • 2015-06-29
    • 1970-01-01
    相关资源
    最近更新 更多