【问题标题】:how do i print out in c++ and linux terminal我如何在 C++ 和 linux 终端中打印出来
【发布时间】:2020-03-16 04:03:58
【问题描述】:
#include <iostream>
#include <vector>
#include <unordered_map>
using namespace std;
class twoSumClass{
    public:
        vector<int> twoSum(vector<int>& nums, int target){
           vector<int> result;
           unordered_map<int,int> hm;
           for(int index = 0; index < nums.size(); index++){
            int findVal = target - nums[index];
            if(hm.count(findVal) > 0 && hm[findVal] != index){
                result.push_back(index);
                result.push_back(hm[findVal]);
                return result;
            }
            else{
                hm.insert(make_pair(nums[index], index));
            }
           }
           return result;
        }
};
void Print(vector<int>& v){
    for (int i = 0; i < v.size(); i++){
        cout << v[i] <<endl;
    }
};
int main(){
    vector<int> items = {1,2,3,4,5,6,7};
    int trgt = 2;
    twoSumClass myTest;
    std::vector<int> res = myTest.twoSum(items, trgt);
    Print(res);
    return 0;
}

这是我的简单代码,我正在尝试在 linux 终端中运行此代码:g++ test1.cpp -o test1,然后运行:./test1 但是,终端不打印任何内容。 我如何更改代码?顺便说一句,代码的目的与 leetcode 问题 #1 相加两个相加。

【问题讨论】:

  • 为什么要问打印出来,却不猜空向量res
  • if(hm.count(findVal) &gt; 0 &amp;&amp; hm[findVal] != index) 永远不会为真,因此向量为空。
  • 这将是在std::vector&lt;int&gt; 中输出值的正确方法。但我认为您的函数不会向您的 res 向量添加任何内容。
  • 如果您进行基本调试,应该很明显这不是打印问题。也就是说,在调试器中运行您的程序并逐步执行代码。
  • 这是一个带有额外打印语句的版本,可以帮助您了解为什么您从未在向量中放入任何内容:onlinegdb.com/HJgJ-qhrL

标签: c++ linux terminal


【解决方案1】:
int main() {
    vector<int> items = {1,2,3,4,5,6,7};
    int trgt = 2;
    ...
}

您想在 向量项 中找出 2 个整数,它们的总和等于 trgt
{1,2,3,4,5,6,7} 中没有答案。
所以没有打印是正确的答案。

建议您阅读此guide

【讨论】:

  • 你说得对,我真的需要注意这一点。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-07-26
  • 2013-01-04
  • 1970-01-01
  • 2012-06-10
  • 2014-11-11
  • 2023-02-18
  • 1970-01-01
相关资源
最近更新 更多