c*****t 发帖数: 1879 | 1 const 一个主要问题是 propagation 。C++ 里面某些情况下会出现一行
代码里面需要七八个 const 。写过 container class 人会有感触,为了
一个 const 有 N 个 implementation 。另外的时候 A 是不和
A 兼容的。所以,很多时候 const 弊大于利。
从另外一个方面来看,代码的很多东西其实不能完全靠 signature 来搞定。
有那么多功夫,把 documentation 写好,比如详细的 JavaDoc 会带来更
多的好处。
至于用 serialization / cloning 等办法,是在并行的情况下,弄一个
snapshot 。比如,shoppingCart.getList() 最好弄个 list clone 。
这样,caller 得到 list 后可以干些花时间的事,却不需要一直 lock
该 shoppingCart 。
其实,我觉得 C++ 的 const 其实就是一种变相的 preemptive optimization。
这是 C++ 语言作者 BS 一个 constradic... 阅读全帖 |
|
y**b 发帖数: 10166 | 2 class HasPtr {
public:
HasPtr(const int &p, int i): ptr(new int(p)), val(i) {}
HasPtr(const HasPtr &orig):
ptr(new int (*orig.ptr)), val(orig.val) { }
HasPtr& operator=(const HasPtr&);
~HasPtr() { delete ptr; }
int get_ptr_val() const { return *ptr; }
int get_int() const { return val; }
void set_ptr(int *p) { ptr = p; }
void set_int(int i) { val = i; }
int *get_ptr() const { return ptr; }
void set_ptr_val(int p) const { *ptr = p; }
... 阅读全帖 |
|
w***g 发帖数: 5958 | 3 我上次去google面试就纠结到这个问题, 那人非要说google要求写const int *p, 所以
这么写是对的. 我跟她解释了半天是int const *p好, 无奈那个面试官是拎不清. 正
确的理解是"const"总是修饰它左边的东西. 所以int const *p是最普适的写法, 可以
推广到类似 int const *const *const **p这样也不会糊涂. |
|
c*****t 发帖数: 1879 | 4 I was interviewing for a principle software engineer / architect
position. The manager also gave me an offline interview question.
I did not give it much thought and sent the solution back. Then
I googled the problem afterward. It was the same as this one.
https://github.com/deepsolo9/interview/tree/master/amazon
The solution there was very bad. Obvious problems you can spot:
1. macros should not be defined in the header file. These macros are
strickly for the implementation, and not for... 阅读全帖 |
|
i**********e 发帖数: 1145 | 5 我已经写了,但是感觉不是最简洁的,所以就没好意思post上来。
我相信有更简洁的版本,所以我还在努力写更简洁的代码。
感觉上递归的方法可以写的更简洁些,但会更加难写对,尤其这问题细节那么多。
注:我没有处理 ‘.’(‘.’match一个的任意字符)。
bool match(const char *str, const char *pattern) {
const char *p1 = pattern, *p2 = str;
while (*p1 && *p1 != '*') {
if (!*p2) return false;
if (*p1 != *p2)
return false;
p1++;
p2++;
}
if (!*p1) {
if (*p2) return false;
else return true;
}
while (*p1) {
while (*p1 == '*')
p1++;
if (!*p1) return true;
const char *p... 阅读全帖 |
|
h*****g 发帖数: 944 | 6 Q1. Which of the following statements about the const qualifier is false?
a) A const variable much be initialized during declaration.
b) no explicit cast is required when converting from non-const to const
c) It is not legal to declare a variable both const and volatile
d) Const pointers are allowed in C
这个是不是选a啊?
Q2. Safe Programming Question
Which of the following will not have undefined behavior?
a) x+= ++i + ++i;
b) i+= ++i;
c) x += ++i;
d) x += ++i + --i;
貌似都能跑啊?到底啥叫underdefined behavior?
Q... 阅读全帖 |
|
y*******i 发帖数: 100 | 7 (a) int i = -1;
(b) const int ic = i;
(c) const int *pic = ⁣
(d) int *const cpi = ⁣
(e) const int *const cpic = ⁣
答案说(d)不合法,其他都合法。d怎么不合法了,不是给一个const 的指针赋值了吗
? |
|
f****4 发帖数: 1359 | 8 const_cast只对变量起作用
const function call non-const function我就找到一个
把non-const重载成const的
void g(){}
void g() const{}
void f() const{ g(); } |
|
i**********e 发帖数: 1145 | 9 我写的 boggle 游戏算法,DFS + trie.
一秒以内给出所有 5x5 的答案。
#include
#include
#include
#include
#include
#include
#include
using namespace std;
struct Trie {
bool end;
Trie *children[26];
Trie() {
end = false;
memset(children, NULL, sizeof(children));
}
void insert(const char *word) {
const char *s = word;
Trie *p = this;
while (*s) {
int j = *s-'A';
assert(0 <= j && j < 26);
if (!p->childre... 阅读全帖 |
|
S**I 发帖数: 15689 | 10 As long as you don't try to modify a declared constant, it is fine. For
example:
void foo(int* p){
//do something with p, but do not change what p points to
}
int main (){
const int a = 2;
const int* b = &a;
foo(b); //error! foo expects int*, not const int*
int* c = const_cast(b);
foo(c); //this is OK
}
Many legacy C codes contain functions like foo, so it is necessary to use
const_cast in these cases.
Another example:
int main(){
int a = 2;
const int* b = &... 阅读全帖 |
|
l*********y 发帖数: 142 | 11 顺手写了一个,46min整。也没用状态压缩,待会看一下gloomyturkey的code。
#include
#include
#include
#include
#include
#include
#include
|
|
z*****n 发帖数: 447 | 12 const char* p;
p is a regular pointer pointing to a const char. You cannot change the
content (*p), but can change p to point another const char.
char* const p;
char const* p;
These two are identical. p is a const pointer pointing to char. You can
change (*p), but you cannot change p to point to another char. |
|
p*i 发帖数: 411 | 13 #include
#include
#include
#include
using namespace std;
inline void swap(int &a, int &b) {
int t = a; a = b; b = t;
}
int partition(vector& work, vector& indices, int p, int q) {
// use work[q] to partition the array
const int x = work[q];
int i = p-1;
for (int j = p; j < q; j++) {
if (work[j] < x) {
i++;
swap(work[i], work[j]);
swap(indices[i], indices[j]);
}
}
i++;... 阅读全帖 |
|
l*********8 发帖数: 4642 | 14 来自主题: JobHunting版 - 请问一道题 Class Union
{
public:
Union(iostream & fin)
{
string a,b;
while(!fin.eof()) {
fin >> a >> b;
Merge(a, b);
}
}
inline Merge(const string &a, const string &b)
{
if (T.count(a) == 0)
T[a] = "";
if (T.count(b) == 0)
T[b] = "";
T[FindRoot[a]] = FindRoot[b];
}
const string & FindRoot(const string & s)
{
if (T[s].empty())
return s;
T[s] = FindRoot(T[s]);
return T[s];
}
inline bool CheckConnection(const string &a, const string &b... 阅读全帖 |
|
d********t 发帖数: 51 | 15 Median of Two Sorted Arrays
There are two sorted arrays A and B of size m and n respectively. Find the
median of the two sorted arrays. The overall run time complexity should be O
(log (m+n)).
解答如下:
问题1> max(0, (m-n)/2)和min(m-1, (m+n)/2)用处是什么
问题2> 这个解答的总体思路是什么
多谢了
double findMedianSortedArrays2(int A[], int m, int B[], int n) {
return findMedianHelper2(A, m, B, n, max(0, (m-n)/2), min(m-1, (m+n)
/2));
};
double findMedianHelper(const int A[], const int m, const int B[], const
int... 阅读全帖 |
|
s********k 发帖数: 6180 | 16 上一个我写的,没有检查字符串是否都在0-9和'.',不知道这个是否需要补上(如果某
个版本不符合要求(10.1.a),返回什么?)。基本思路是第一个.之前按照数字大小比较
,然后其余的一个个位置比较,只要某一个位置其中一个大,剩下的就不需要比较了(比
如2.07和2.1,小数点之后后面的1》前面的0,直接2.1版本大),然后如果某个字符串先
到.,别的还有数字,那么后者大(1.05>1.0.5),如果最后一个已经晚了,另外一个还有
数字,后面大(3.2.1<3.2.10或者3.2.1<3.2.1.5)
大牛指点一下
const char *compVersion(const char *version1, const char * version2){
const char *v1 = version1;
const char *v2 = version2;
//compare the digit before first '.'
if(getNum(v1)>getNum(v2)) return v1;
else if(getNum(v1)>ge... 阅读全帖 |
|
f*******t 发帖数: 7549 | 17 找出了一年多前写的逆波兰处理算数表达式的代码,强烈建议有兴趣的自己实现一下:
#include
#include
#include
#include
#define BUFFSIZE 1024
using namespace std;
struct Token {
bool isNum;
int num;
char op;
Token();
Token(const Token& t);
};
Token::Token()
{
isNum = false;
num = 0;
op = 0;
}
Token::Token(const Token& t)
{
isNum = t.isNum;
num = t.num;
op = t.op;
}
Token *getToken(const char expr[], int& idx)
{
Token *res = NULL;
while(expr[idx] == ' ')
... 阅读全帖
|
|
x******a 发帖数: 6336 | 18 Thanks a lot! it worked.
再请教一个问题:我想历遍一个通过frontinsert生成的linkedlist,为什么看不到第
一个insert的元素?谢谢
#include
#include "singlylinkedlist.h"
int main(int argc, const char * argv[])
{
SingleLinkedList aList;
int i=0;
while(i<10){
aList.firstInsert(i);
++i;
}
aList.traverse();
}
输出是
9 8 7 6 5 4 3 2 1
没有0
template< typename T> class ListElement;
template< typename T> class SingleLinkedList;
template
class ListElement{
public:
ListElement(cons... 阅读全帖 |
|
r***e 发帖数: 29 | 19 我的答案(C++):
#pragma once
#ifndef _ROMON_HEADER_
#define _ROMON_HEADER_
#include
#include
using namespace std;
const string ROMON_DIGIT[] = {"","I","II","III","IV","V","VI","VII","VIII","
IV"};
//ROMON 0-9
const int ROMON_SCALE[] = {10, 50, 100, 500, 1000};
const char ROMON_SCALE_REP[] = {'X', 'L', 'C', 'D', 'M'};
//ROMON scale
const int ROMON_MAX = 3999;
const int ROMON_MIN = 1;
// rewrite the interface
class RomanNumeralGenerator
{
public:
virtual string generator(int n... 阅读全帖 |
|
s*******s 发帖数: 1031 | 20 follow一下我的面经。
http://www.mitbbs.com/article_t/JobHunting/32517841.html
整理了我的几个解答的算法,分享一下。欢迎批评指正。
多谢!
1. 写一个程序,找出 5^1234566789893943的从底位开始的1000位数字。
我用的递归+数组大数乘法。
// Caclulate (m^n)%(10^k). Keep the k integer numbers in an array.
// Note: the integer numbers are in reversed in the array
// Assume: m>0, n>0, k>0
// Need to check validity outside of this function.
// call calculate(5, 1234566789893943, 1000) to get result.
// Time complexity: O((log n) * k * k)
// Space complexity: O((log n) * k)
ve... 阅读全帖 |
|
f**********t 发帖数: 1001 | 21 class Intervals {
vector> _vals;
public:
Intervals(initializer_list> prs) {
_vals.insert(_vals.end(), prs.begin(), prs.end());
}
void Dump() {
for_each(_vals.begin(), _vals.end(), [](const pair &p) {
cout << '(' << p.first << ',' << p.second << ')' << ", ";
});
cout << endl;
}
void Insert(const pair &pr) {
auto left = lower_bound(_vals.begin(), _vals.end(), pr,
[](const pair &x, const pair阅读全帖 |
|
A*********c 发帖数: 430 | 22 你这个代码,我觉得有点略长。你看这个你能不能改成java的。
class Solution {
public:
void solve(vector> &board) {
if (board.size() == 0) return;
const int m = board.size(); const int n = board[0].size();
queue> q;
for (int i = 0; i < m; ++i) {q.push({i, 0}); q.push({i, n-1});}
for (int j = 1; j < n-1; ++j) {q.push({0, j}); q.push({m-1, j});}
while (!q.empty()) {
pair p = q.front(); q.pop();
int i = p.first, j = p... 阅读全帖 |
|
|
|
I**********n 发帖数: 77 | 25 -------
美国CS面试工作交流群QQ: 167615205
--------
看下面的code
#include
#include
#include |
|
t**r 发帖数: 3428 | 26 贴个答案
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
|
|
d**********o 发帖数: 1321 | 27 第一个项目report
这时偶刚到CSAC工作不久,与小A同学还不熟,我用的还是latex。随着贴的作业越来越
多,应该是用有共同爱好的小伙伴更亲密些。这次贴latex,下次才再org-mode。
\documentclass[b5paper,11pt, abstraction, titlepage]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{CJKutf8}
\usepackage{multirow}
\usepackage{multicol}
\usepackage{listings}
\usepackage{geometry}
\geometry{b5paper}
\usepackage{graphicx,floatrow}
\usepackage{graphicx,subfigure}
\newsavebox{\abstractbox}
\renewenvironment{abstract}
{\begin{lrbox}{0}\begin{minipage}{\t... 阅读全帖 |
|
d**********o 发帖数: 1321 | 28 第一个项目report
这时偶刚到CSAC工作不久,与小A同学还不熟,我用的还是latex。随着贴的作业越来越
多,应该是用有共同爱好的小伙伴更亲密些。这次贴latex,下次才再org-mode。
\documentclass[b5paper,11pt, abstraction, titlepage]{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{CJKutf8}
\usepackage{multirow}
\usepackage{multicol}
\usepackage{listings}
\usepackage{geometry}
\geometry{b5paper}
\usepackage{graphicx,floatrow}
\usepackage{graphicx,subfigure}
\newsavebox{\abstractbox}
\renewenvironment{abstract}
{\begin{lrbox}{0}\begin{minipage}{\t... 阅读全帖 |
|
C****n 发帖数: 2324 | 29 All right guys.
1. Const can not be changed, and can only be declared in the field
declaration.
i.e.: public const int i=5;
2. const automatically means static.
3. Readonly can be asigned in CONSTRUCTOR!
The real world concern:
Never declare a public field as CONST (static), use readonly
instead, which will save you from recompilation if the const in the underlying
library is
recompiled. Only use const with your private field.
Well, a better pratice is never declare public field.
The Count in Ar |
|
q*********u 发帖数: 280 | 30 我来一个具体的好了,看了一下programming和这里的,发现自己懂和表达清楚完全两
码事起。其中有一个老兄凶神恶煞的,看了都一怔。
#include
using namespace std;
class T
{
public:
T(){a = 11;}
int Get() const{return a;}
private:
int a;
};
class Test
{
public:
Test(int a):m_a(a){}
Test(const Test &t){m_a = t.m_a;} //拷贝构造函数,通过同类型的引用参数访问
私有变量
Test& operator=(const Test &t) //赋值操作函数,通过同类型的引用参数访问私
有变量
{
m_a = t.m_a;
}
//Test(const T &t){m_a = t.a;} //此语句出错,不能访问T类型的私有成员
Test(const T &t){m_a = t.Get();} //这个实现可以
void Print() const
{
cout<<"m_a: |
|
y****i 发帖数: 156 | 31 ///
// Change reference to pointer
#include
class index_object_1;
class index_object_2;
class index_object_2_comparator
{
public:
bool operator() (const index_object_2 * lhs, const index_object_2 * rhs)
const
{
return true;
}
};
class index_object_1_comparator {
public:
bool operator() (const index_object_1 * lhs, const index_object_1 * rhs)
const
{
return true;
}
};
class index_object_1 {
private:
double index;
std::set |
|
g****c 发帖数: 299 | 32 Basic String Handling Functions
All the string handling functions are prototyped in:
#include
The common functions are described below:
char *stpcpy (const char *dest,const char *src) -- Copy one string into
another.
int strcmp(const char *string1,const char *string2) - Compare string1 and
string2 to determine alphabetic order.
char *strcpy(const char *string1,const char *string2) -- Copy string2 to
stringl.
char *strerror(int errnum) -- Get error message corresponding to specified
er |
|
O*******d 发帖数: 20343 | 33 来自主题: Programming版 - 数学的美 上边函数用到的几个参数
const unsigned int WIDTH = 1500U;
const unsigned int HEIGHT = 1000U;
const double RATIO = (double)HEIGHT /(double)WIDTH;
/* zoom is calibrated to width 1000 */
const double ZOOM = 0.000000001 * (double)WIDTH / 1000.0 ;
const double ZOOM_Y = ZOOM * RATIO;
const int MAX_ITER = 1800;
/* x and y center of the image */
double xOffset = -0.713;
double yOffset = 0.34; |
|
c*****a 发帖数: 55 | 34 A function header define is like:
aaa(const char *&x, const char *&y);
我这么implement 可以么?怎么给char *&类型负值尼?
const char *a;
const char *b;
aaa(const char *&x, const char *&y)
{
x=(char *&)a;
y=(char *&)b;
}
Thanks a lot. |
|
s****y 发帖数: 4 | 35 actually three:
1. what's the difference of
const char* p
char const *p
char* const p
what i understood is---first is a pointer to constant object;
second and third are same , a constant pointer to an object
am i right?
2. is this true:
const char* p = const char *p
3. why const char* can be both a character and a string declaration |
|
t****t 发帖数: 6806 | 36 其实就是记住, temp object只能bind to const reference就行了
比如说
const int& j=1; //valid
int& j=2; //invalid
虽然这样显式的写法比较少, 但是temp object bind to const reference在函数调用
时还是非常常见的.
比如说
class complex {
public:
complex(double);
};
complex operator+(const complex&, const complex&);
complex a=1;
complex c=a+2;
最后那一行, 实际上做的是
complex c=operator+(a, complex(2));
complex(2)是个临时对象, 必须bind to const reference. 如果op+改成
complex operator+(complex&, complex&);
就不能这么写了.
can |
|
j*****k 发帖数: 1198 | 37 effective c++里面说:
In particular, if the object this points to is truly const, i.e., was
declared const at its point of definition, the results of casting away its
constness are undefined. If you want to cast away constness in one of your
member functions, you'd best be sure that the object you're doing the
casting on wasn't originally defined to be const.
这儿是不是指如果the object is originally defined to be a const, the casted
result can not be used as lvalue? 如果是这样的话,下面就可以理解了。如果不是
,那是什么意思呢?
size_t st |
|
z***e 发帖数: 5393 | 38 嗯,我觉得也是。
lz 的两个read() function是完全不同的:
template
void read(const Location &, const char * dataset_name, T & matrix);
//这个declare了,但是下面并不是definition. 第三个参数类型都不同。
template
void
read(const Location &location, const char *dataset_name, SArray::
Array & arr) {} // this function is not found
}
然后lz:
Array arr;
M::read_matrix("file", "location", arr);
arr是Array---这个就是你的type,相当于:
void read(const Location &, const char * dataset_name, Array &
mat |
|
g****n 发帖数: 14 | 39 抛砖引玉吧 :)
const int DAYS_80_99 = 20 * 365 + 5;
const int CYCLE_400 = 365 * 400 + 97;
const int CYCLE_100_L = 365 * 100 + 25;
const int CYCLE_100_N = 365 * 100 + 24;
const int CYCLE_4_L = 365 * 4 + 1;
const int CYCLE_4_N = 365 * 4;
// input: cDay - number of days since Jan 1, 1980.
// For Jan 1, 1980, cDay==0
// output: year, day (this first day of a year is represented as 0).
void year(int cDay, int& year, int& day)
{
int days = cDay;
int years = 1980;
if (days >= DAYS_80_99)
|
|
k**f 发帖数: 372 | 40
Usually const is used along with pointer or reference in the return type.
The returned value can only be assigned to a const pointer or bonded to a
const reference. If the underlying type is a class (struct), only the const
method can be called using such const pointers and references.
Otherwise, if you return a non-const pointer or reference, you can change
the object through the pointer or reference. |
|
e****d 发帖数: 333 | 41 来自主题: Programming版 - C++一问 关于函数参数是const type &的问题。
一般写成这样
void f(const type & para){...}
如果type是指针,应该怎么版呢?是
const type* &p
还是
type* const &p
还是用两个 const 好呢?
就是说,一般是根据情况决定呢?还是有一个规则?
我比较倾向用
type* const &p
这样可以兼容数组,比如:
int A[3]={1,2,3}.
f(A);
请问实际中哪种比较好呢? |
|
L*******s 发帖数: 63 | 42 编译器好像是 g++ 4.3.4
struct eqstr
{
inline bool operator()(const char* s1, const char* s2) const
{
return 0 == strcmp(s1, s2);
}
};
typedef __gnu_cxx::hash_map
>, eqstr> MyTable;
现在有
MyTable t;
中途进行一系列添加操作
每隔一段时间进行以下输出
std::cout << t.size() << std::endl;
std::for_each(t.begin(), t.end(), display1);
display1如下:
void display1(std::pair pr)
{
std::cout << (pr.second ? "T " : "F ") << pr.first << std::endl;
}
我现 |
|
X****r 发帖数: 3557 | 43 int mystrcmp(const void * str1, const void * str2)
{
return strcmp(*(const char* const*)str1, *(const char* const*)str2);
}
doesn |
|
h*******s 发帖数: 8454 | 44 en 比较的这些operator都是global的
bool operator== ( const string& lhs, const string& rhs );
bool operator== ( const char* lhs, const string& rhs );
bool operator== ( const string& lhs, const char* rhs ); |
|
s*******e 发帖数: 664 | 45 ☆─────────────────────────────────────☆
PaulPierce (Paul) 于 (Mon Aug 31 16:51:16 2009, 美东) 提到:
我优点糊涂了,搞不清楚:
关于static const,下面程序有static怎么可以通过 compile.
不过如果我const去掉,就通不过,很正常。const难道可以把static作用取消?
比如我有三个file a.h, a.cpp, main.cpp
//a.h
extern const int i;
//a.cpp
#include "a.h"
static const int i = 3;
//main.cpp
#include "a.h"
int main()
{
return i;
}
☆─────────────────────────────────────☆
SuperString (小芝麻他爹) 于 (Mon Aug 31 16:59:56 2009, 美东) 提到:
without const
you have two conflicting ve |
|
z****e 发帖数: 2024 | 46 master shifu:
ie. a const data member in a class, this const is going to be initialized in
the constructor initialization list, is it a "global" const, or is it the
same as a regular const?
when an object of the above class is instantiated, this const member data
will be initialized. but if no object is constructed, is this const member
data going to be initialized?
that's something always confusing me. |
|
j***i 发帖数: 1278 | 47 这个c++ primer 里面有
template 一般不会有conversion 直接会生成一个新的instantion
但是如果 T 是指向const 元素的指针或者reference,可以用非const的match,这就是
说,const 和non const 共用一个实现
第一个程序,template吧 吧T 替换为 int * 是perfect match,
因为 const int * 和 int* 对于template都一样的,
plain 的版本还有一个implicit 的转换从 int* 到const int* 所以选了template
你可以去找找c++ primer 解释的很清楚的 |
|
o**********a 发帖数: 330 | 48 class A {
public:
A(const int, const vector&);
A(const A&);
virtual A& operator=(const A&);
//...
protected:
int i;
vector s;
};
A::A(const int a,const vector& b):i(a),s(b){}
//我这么写没有定义defualt constructor,请问如何定义这个constructor
//另外,一般写类的时候,是不是最好都定义default contructor |
|
p*u 发帖数: 2454 | 49
anywhere by
setter/
you are right, but we can always solve this with another level of
indirection:
"
#define GETTER( a ) Intruder::get( *this, a )
#define SETTER( a, i ) Intruder::set( *this, a, i )
class A
{
private:
friend struct Intruder;
int _i;
};
struct Intruder
{
template
static int get( const T& ref, const A& a );
template
static void set( const T& ref, A& a, int i );
};
template
int Intruder::get( const T& ref, const A& a )... 阅读全帖 |
|
g*********s 发帖数: 1782 | 50 The following code has compilation errors if "-DDEBUG" is not specified.
In function `StripePainter::init_tab(std::basic_string
std::char_traits, std::allocator >)':
inclass_static.cpp:(.text+0xb): undefined reference to
`StripePainter::colorset'
inclass_static.cpp:(.text+0x1b): undefined reference to
`StripePainter::orig_color'
inclass_static.cpp:(.text+0x23): undefined reference to
`StripePainter::colorset'
inclass_static.cpp:(.text+0x58): undefined reference to
`StripePainte... 阅读全帖 |
|