c++ 笔试题2

2014-11-24 09:55:12 · 作者: · 浏览: 0

1.socket中能传输结构体吗

不能,因为结构体的大小与内存对齐,不能保证发送方和接收方是同样的机器同样的系统,传输结构体的话会导致数据紊乱。

2.实现一个队列,使用单链表还是双链表好?如何实现?

使用双向链表好,因为单链表不便在末尾添加元素。可通过list来代理实现,基体的代码如下:

#ifndef _QUEUE
#define _QUEUE
#pragma once
#include 
  
   
#include 
   
     using std::list; using std::cout; using std::endl; typedef int Data; typedef list
    
     ::iterator iterator; typedef list
     
      ::const_iterator const_iterator; typedef list
      
       ::size_type size_type; class Queue { private: list
       
         l; public: bool isEmpty() { return l.empty(); } void push(const Data &data) { l.push_back(data); } //出队列 Data& deQueue() { Data &data = l.front(); l.pop_front(); return data; } //取队头元素 Data& peek() { return l.front(); } Queue(){} ~Queue(){} }; #endif void testQueue() { Queue q; q.push(1); q.push(3); q.push(5); q.push(7); cout << q.peek() << endl; q.deQueue(); cout << q.peek() << endl; q.deQueue(); cout << q.peek() << endl; }
       
      
     
    
   
  


3.选择1、4、5中的的任意个数使它们的和为100,共有多少种选择方案?

int num[] = {1,4,5};
int getSum(int n) {
    int count = 0;
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= n; j++) {
            for (int k = 0; k < n; k++) {
                if (num[0] * i + num[1] * j + num[2] * k == n) {
                     //cout << num[0] << "*" << i << "+" << num[1] << "*" << j << "+" << num[2] << "*" << k << "=" << num[0] * i + num[1] * j + num[2] * k << endl;
                    count++;
                }
            }
        }
    }
    return count;
}